Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

python - How do I extend the Django Group model?

Is there a way to extend the built-in Django Group object to add additional attributes similar to the way you can extend a user object? With a user object, you can do the following:

class UserProfile(models.Model):
    user = models.OneToOneField(User)

and add the following to the settings.py file

AUTH_PROFILE_MODULE = 'app.UserProfile'

which gets you:

profile = User.objects.get(id=1).get_profile()

Is there any equivalent to this approach for extending a group? If not, is there an alternative approach I can take?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you simply subclass the Group object then by default it will create a new database table and the admin site won't pick up any new fields.

You need to inject new fields into the existing Group:

if not hasattr(Group, 'parent'):
    field = models.ForeignKey(Group, blank=True, null=True, related_name='children')
    field.contribute_to_class(Group, 'parent')

To add methods to the Group, subclass but tag the model as proxy:

class MyGroup(Group):

    class Meta:
        proxy = True

    def myFunction(self):
        return True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...