只是想添加一些我在其他答案中没有看到的东西。
与python类不同,不允许隐藏字段名称模型继承。
例如,我对用例进行了如下实验:
我有一个从Django的auth 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,除其他外,我还希望它覆盖related_name
该groups
字段。所以或多或少是这样的:
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个mixins如下:
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'
如您所见,此错误确实说明了发生了什么。
在我看来,这是一个巨大的差异:)