开发者

Extending a field of a contrib model in Django

开发者 https://www.devze.com 2023-02-16 19:01 出处:网络
I have come across this situation several times. If I have something that I generally like in contrib, but I want to make one minor tweak to a field, what do I do?

I have come across this situation several times.

If I have something that I generally like in contrib, but I want to make one minor tweak to a field, what do I do?

I don't want to throw out the baby with the bathwater.

To give an example, take auth.user (which, contrary to what seems to be popular opinion on the matter, I regard as being generally on the right track)开发者_如何学编程. I want to create a through model for auth.user's relationship to auth.group.

How can I do this without modifying django?


auth.User is a special case since the User model is tied in to lots of parts of Django and it is tricky to modify this (though not impossible, as others have pointed out). My best advice would be to question why you don't want to modify Django source. You can pull source for either the head of the devel branch or get a tagged version corresponding to a numbered release. Modify the code at will and use some combination of svn update, svn diff, and svn patch to migrate your changes.

Next, modifications to contrib modules are possible in your code, since Python is interpreted and dynamically typed. If you do this, you'll need to take into consideration parsing/processing order since some operations may already have utilized the original module. Below is an example I got from someone else (probably here on SO) of how to add a convenient forward reference from User to the associated Profile object:

from django.db.models import Model
from django.contrib.auth.models import User

class UserProfile(Model):
    user = ForeignKey(User, unique=True)
    phone = CharField(verbose_name="phone number", blank=False, max_length='20')

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

I don't think this strategy will work for adding/modifying ModelFields in django.contrib.auth.models.User, however.

Finally, for your specific example of associating groups with a user, you should see if this is possible by creating a UserProfile model. My initial guess is that it should be pretty easy.

0

精彩评论

暂无评论...
验证码 换一张
取 消