我想补充一些其他答案中没有提到的内容。
与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,其中我希望它覆盖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.'))
我使用了以下两个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'
正如您所看到的,这个错误确实解释了正在发生的事情。
这是一个巨大的区别,在我看来 :)