Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...