【问题标题】:Combining abstract model class and multi-table inheritance in Django在Django中结合抽象模型类和多表继承
【发布时间】:2013-08-31 11:33:07
【问题描述】:

我有三个模型类:

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

mysite.models.Profile,简称Profile

mysite.models.Subscriber,简称Subscriber

Profile 继承自 User 的方式类似于 docs 中的 well described,作为一种解决方案,可以将自定义属性添加到 User 模型,而无需打扰可交换模型(仅在 1.5 版中添加)。

虽然ProfileSubscriber 是不同的对象,但它们确实共享一些属性。即,我想同时使用自定义主键算法,并以类似的方式覆盖save()方法,以便可以按照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不会冲突吗?

【问题讨论】:

    标签: python django multiple-inheritance


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 是的,没关系,不,我想要 blank=True 和 null=True :) 我想要的是 Profile 对象上可用的 User 字段,但似乎它不符合抽象模型类,所以我求助于这个解决方案。
    猜你喜欢
    • 2013-11-29
    • 2013-12-22
    • 2023-03-05
    • 2018-03-07
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多