python - Django中抽象模型类与多表继承的结合

标签 python django multiple-inheritance

我有三个模型类:

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

mysite.models.Profile,称为Profile

mysite.models.Subscriber,称为Subscriber

Profilewell described 的方式继承自 User在文档中作为向 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不会发生冲突吗?

最佳答案

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

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

但是,我怀疑您实际上并不希望空白=True 和 null=True 存在其中。

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

关于python - Django中抽象模型类与多表继承的结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18547669/

相关文章:

python - SQLAlchemy:避免多重继承并拥有抽象基类

generics - 有什么方法可以在 Kotlin 中从相同的通用接口(interface)继承两次(使用不同的类型)?

java - Java 中的重叠继承

python - 使用 python centos-7 安装 theano

python - 在 Django REST 框架中优化数据库查询

django - Google Oauth 2.0 网络应用程序 "Authorized redirect URIs"必须以公共(public)顶级域(例如 .com 或 .org)结尾?

python - 开发新网络应用程序的平台

python - Python 有包/模块管理系统吗?

python - twisted.web.resource.Resource 和 twisted.web.template.Element 示例

Django:如何更改 django-tables2 中的列宽