只是想添加一些我在其他答案中没有看到的东西。
与 python 类不同,field name hiding is not permited 具有模型继承。
例如,我对一个用例进行了如下实验:
我有一个模型继承自 django 的身份验证 PermissionMixin:
class PermissionsMixin(models.Model):
"""
A mixin class that adds the fields and methods necessary to support
Django's Group and Permission model using the ModelBackend.
"""
is_superuser = models.BooleanField(_('superuser status'), default=False,
help_text=_('Designates that this user has all permissions without '
'explicitly assigning them.'))
groups = models.ManyToManyField(Group, verbose_name=_('groups'),
blank=True, help_text=_('The groups this user belongs to. A user will '
'get all permissions granted to each of '
'his/her group.'))
user_permissions = models.ManyToManyField(Permission,
verbose_name=_('user permissions'), blank=True,
help_text='Specific permissions for this user.')
class Meta:
abstract = True
# ...
然后我有了我的 mixin,我希望它覆盖 groups 字段的 related_name。所以它或多或少是这样的:
class WithManagedGroupMixin(object):
groups = models.ManyToManyField(Group, verbose_name=_('groups'),
related_name="%(app_label)s_%(class)s",
blank=True, help_text=_('The groups this user belongs to. A user will '
'get all permissions granted to each of '
'his/her group.'))
我使用这 2 个 mixin 如下:
class Member(PermissionMixin, WithManagedGroupMixin):
pass
是的,我希望这会起作用,但它没有。
但是问题更严重,因为我得到的错误根本没有指向模型,我不知道出了什么问题。
在尝试解决这个问题时,我随机决定更改我的 mixin 并将其转换为抽象模型 mixin。错误变成了这样:
django.core.exceptions.FieldError: Local field 'groups' in class 'Member' clashes with field of similar name from base class 'PermissionMixin'
如您所见,这个错误确实解释了发生了什么。
在我看来,这是一个巨大的差异:)