【问题标题】:How to implement two abstract models with ForeignKey relation of one to other in Django?如何在Django中实现两个具有相互外键关系的抽象模型?
【发布时间】:2018-08-01 16:52:45
【问题描述】:

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

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)

【问题讨论】:

标签: django models


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 2015-12-04
      • 2011-11-23
      • 2012-07-21
      • 2020-12-23
      • 2023-01-26
      相关资源
      最近更新 更多