django - 如何在 Django 中实现两个具有彼此外键关系的抽象模型?
问题描述
即我们有SomeSeries
几个SomeDecor
s,其中 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)
解决方案
您不能创建ForeignKey
引用抽象模型。它甚至没有任何意义,因为ForeignKey
转换为必须引用现有表的外键约束。
作为一种解决方法,您可以创建GenericForeignKey字段。
推荐阅读
- sql - 更新同一表中引用不同 id 的值
- python - 为什么在分配错误之前收到以下代码的引用
- c# - LINQ to XML - 无法从 XDocument 或 XElement 读取元素或后代
- javascript - Vue 测试工具。在不是 .vue 文件的子组件上触发点击事件
- ruby-on-rails - `load_missing_constant':在自动加载常量 ApplicationRecord (RuntimeError) 时检测到循环依赖
- excel - 如何让多个无模式 VBA 表单在 Excel 上运行
- python - 如何在 Windows 上在 python 中删除 git 存储库
- svg - 沿 SVG 中的路径定位对象
- xml - Oracle DB - 在数据库中保存时间戳
- c# - asp .net core 3 本地化问题导致页面中断