2

我有三个模型类:

django.contrib.auth.models.User,简称为User

mysite.models.Profile,简称为Profile

mysite.models.Subscriber,简称为Subscriber

Profile以一种在文档中很好地描述User的方式继承自,作为向模型添加自定义属性而无需打扰可交换模型(仅在 1.5 版中添加)的解决方案。User

虽然ProfileSubscriber是不同的对象,但它们确实共享一些属性。即,我想以save()类似的方式将自定义主键算法与 both 和 override 方法一起使用,以便可以按照 DRY 重用代码。现在,如果两者都是简单的模型类,那就很简单了:

class BaseProfile(models.Model):
    key = models.PositiveIntegerField(primary_key=True)
    activated = models.BooleanField(default=False)
    ...

    class Meta:
        abstract = True

    def save():
        ...

class Profile(BaseProfile):
   ...

class Subscriber(BaseProfile):
   ...

但是,Profile 已经使用了多表继承。我正在考虑类似的方法:

class BaseProfile(models.Model):
    key = models.PositiveIntegerField(primary_key=True)
    activated = models.BooleanField(default=False)
    ...

    class Meta:
        abstract = True

    def save():
        ...

class Profile(BaseProfile, User):
    user = models.OneToOneField(User, parent_link=True, blank=True, null=True, on_delete=models.CASCADE)
    ...

class Subscriber(BaseProfile):
   ...

那可能吗?如果是这样,在我的情况下需要什么继承顺序,以便save()以正确的方式调用模型字段和方法?两个模型类的 Meta 不会发生冲突吗?

4

1 回答 1

2

您链接到的文档没有描述通过多表继承从用户继承。它确实解释了您可以使用 OneToOneField 链接类似“个人资料”的对象。尝试:

class Profile(BaseProfile):
    user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE)
    ...

但是,我怀疑您实际上并不想要 blank=True 和 null=True 。

这种方法确实意味着您的 User 对象很可能没有与其对应的 Profile 对象相同的主键,但这对您来说可能没问题。

于 2013-08-31T13:52:34.167 回答