首页 > 解决方案 > 如何在 Django 中实现两个具有彼此外键关系的抽象模型?

问题描述

即我们有SomeSeries几个SomeDecors,其中 ForeignKeySomeDecor指向SomeSeries。我希望两者都是抽象的,然后再实例化几对它(在数据库中有自己的表)。可能吗?IE

class SomeSeries(models.Model):
    class Meta:
        abstract = True

    vendor = models.ForeignKey(Vendor)
    name = models.CharField(max_length=255, default='')
    def __unicode__(self):
        return "{} {}".format(self.vendor, self.name)


class SomeDecor(WithFileFields):
    class Meta:
        abstract = True

    series = models.ForeignKey(SomeSeries) # some magic here to make ForeignKey to abstract model
    texture = models.ImageField()
# -------------------------------------------
class PlinthSeries(SomeSeries): pass
class PlinthDecor(SomeDecor): pass
# Some magic to make PlinthDecor.series points to PlinthSeries  

编辑实际上我不想要多态关系的共谋,我想要纯抽象模型只是为了节省打字(抽象模型最初是为了什么)。假设在我的情况下,最简单的方法是从基本模型中排除 ForeignKey 并仅在所有继承模型中键入它:

class SomeSeries(models.Model):
    class Meta:
        abstract = True
    #...

class SomeDecor(WithFileFields):
    class Meta:
        abstract = True

    series = None #?
    #..
    texture = models.ImageField()

    def do_anything_with_series(self): pass

class PlinthSeries(SomeSeries): pass
class PlinthDecor(SomeDecor): pass
    series = models.ForeignKey(PlinthSeries)

标签: djangomodels

解决方案


您不能创建ForeignKey引用抽象模型。它甚至没有任何意义,因为ForeignKey转换为必须引用现有表的外键约束。

作为一种解决方法,您可以创建GenericForeignKey字段。


推荐阅读