如何在Django中实现彼此之间具有ForeignKey关系的两个抽象模型?

时间:2018-08-01 16:52:46

标签: django models

即我们有SomeSeries和几个SomeDecor,其中SomeDecor的ForeignKey指向SomeSeries。我想既要抽象又要实例化几对(在db中有它自己的表)。可能吗? 即

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)

2 个答案:

答案 0 :(得分:2)

您无法创建引用抽象模型的ForeignKey。甚至没有任何意义,因为ForeignKey转换为Foreign Key Constraint,必须引用现有表。

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

答案 1 :(得分:0)

您不能这样做,因为如果创建了两个从抽象类继承到您的外键应该做什么的类,则该继承吗?第一还是第二? 因此,您需要创建GenericForeignKey或不创建任何字段,只有在create model从抽象模型继承后,再添加外键。