2

如果模型不是,有没有办法从现有模型继承以复制其所有字段(以 DRY 方式)而不调用多表继承abstract

需要明确的是,我有一个模型Post,并且我希望有另一个模型在可用字段方面完全GhostPost反映Post,但我希望它具有多表继承或与Post. 问题是,Post不是抽象模型,所以 Django 会发起多表继承。有没有解决的办法?

更新:我在这里寻找的不是模型的 Python 级副本,而是反映这些字段的实际独立数据库表。

解决方案:我遵循@Brandon 的建议并使用了抽象模型。

4

2 回答 2

3

在这种情况下,您需要使用代理模型。它将允许您扩展一个非抽象但没有多表继承的模型:https ://docs.djangoproject.com/en/1.6/topics/db/models/#proxy-models

代理模型将保留一个单表,因此如果每个模型都需要一个表,我建议创建一个通用抽象类来继承PostandGhostPost模型。

于 2014-07-26T02:26:46.057 回答
0

您可以添加一个额外的 BooleanField is_ghost,并覆盖原始模型和代理模型上的默认管理器:

class PostManager(models.Manager):
    def get_querset(self):
        return super(PostManager, self).get_queryset().filter(is_ghost=False)

class Post(models.Model):
    ...
    is_ghost = models.BooleanField(blank=True, default=False)
    objects = PostManager()

class GhostPostManager(models.Manager):
    def get_queryset(self):
        return super(GhostPostManager, self).get_queryset().filter(is_ghost=True)

class GhostPost(Post):
    objects = GhostPostManager()

    Meta:
        proxy = True

这会将所有内容保存在一个表中,但管理器和查询集将像两个单独的模型/表一样工作。

另一种解决方案是对两个模型都使用抽象基类。如果您不更改原始Post模型的类名,并从 eg 继承AbstractPost,我认为这不会导致任何问题。

于 2014-07-26T10:01:57.803 回答