我最初只扩展了Group模型,虽然我让额外的字段正常工作,但当我切换回auth-user模型时,我最终会得到不一致的结果:
group1 = MyGroup(..)
user = group1.user_set.all()[0]
group2 = user.groups.all()[0]
group1 == group2 #(False!)
type(group1) #MyGroup..
type(group2) #Group..
我的下一个想法是扩展auth.User和auth.Group模型。
示例结构:
from django.contrib.auth.models import User As DjangoUser
from django.contrib.auth.models import Group As DjangoGroup
class MyGroup(DjangoGroup):
extra1 = models.CharField(..)
class MyUser(DjangoUser):
extra1 = models.CharField(..)
这可能吗? I saw a bug-report stating it was fixed here.但是我没有看到实现这一目标的正确方法的示例,也不清楚错误修复后这部分是否必要:
manager = UserManager()
class MyUser(DjangoUser):
signature = forms.CharField()
post_count = forms.IntegerField()
objects = manager
_default_manager = manager
这种行为的任何想法/例子?我试图在用户模型中重新定义“组”链接,但这导致了验证错误。理想情况下,我希望能够运行上面的示例并使group1 == group2和type(group2)== type(MyGroup())
答案 0 :(得分:0)
您可以向django用户/组模型动态添加新字段,这样就不会创建新的类类型。有关参考,请参阅:http://code.google.com/p/comaie-django-groups/source/browse/trunk/src/comaie/django/groups/models.py?r=5
models.ForeignKey( Group, null = True, blank = True, related_name = 'children', verbose_name = _('parent'), help_text = _('The group\'s parent group. None, if it is a root node.') ).contribute_to_class(Group, 'parent') def get_all_groups(self): """ Returns all groups the user is member of AND all parent groups of those groups. """ direct_groups = self.groups.all() groups = set() for group in direct_groups: ancestors = group.get_ancestors().all() for anc in ancestors: groups.add(anc) groups.add(group) return groups setattr(User, 'get_all_groups', get_all_groups)