如何扩展Django Group模型? [英] How do I extend the Django Group model?
问题描述
有没有办法扩展内置的Django Group对象来添加类似于扩展用户对象的其他属性?使用用户对象,您可以执行以下操作:
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)
并将以下内容添加到settings.py文件
and add the following to the settings.py file
AUTH_PROFILE_MODULE = 'app.UserProfile'
可以得到你:
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?
推荐答案
您可以创建一个子类Group的模型,添加您自己的字段,并使用模型管理器返回您需要的任何自定义查询集。以下是截断的示例,显示我扩展了组以表示与学校相关联的家庭:
You can create a model that subclasses Group, add your own fields, and use a Model Manager to return any custom querysets you need. Here's a truncated example showing I extended Group to represent Families associated with a school:
from django.contrib.auth.models import Group, User
class FamilyManager(models.Manager):
"""
Lets us do querysets limited to families that have
currently enrolled students, e.g.:
Family.has_students.all()
"""
def get_query_set(self):
return super(FamilyManager, self).get_query_set().filter(student__enrolled=True).distinct()
class Family(Group):
notes = models.TextField(blank=True)
# Two managers for this model - the first is default
# (so all families appear in the admin).
# The second is only invoked when we call
# Family.has_students.all()
objects = models.Manager()
has_students = FamilyManager()
class Meta:
verbose_name_plural = "Families"
ordering = ['name']
def __unicode__(self):
return u'%s' % (self.name)
这篇关于如何扩展Django Group模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!