【发布时间】:2010-11-10 00:42:00
【问题描述】:
基本上,我有一个模型,其中我创建了许多其他类共享的超类,然后这些类中的每一个都有一些彼此不同的独特功能。假设 A 类是超类,B、C 和 D 类是该类的子类。
B 类和 C 类都可以有 D 类的倍数,但是我发现最好将外键关系放在 D 类中,然后它引用它的父类。现在在其他语言中,我可以简单地说它与 A 类有 ForeignKey 关系,然后该语言会识别类的真实类型。但是,我不认为 Python 就是这样工作的。
解决此问题的最佳推荐方法是什么?
编辑:这就是我的意思...
class A(models.Model):
field = models.TextField()
class B(A):
other = <class specific functionality>
class C(A):
other2 = <different functionality>
class D(A):
#I would like class D to have a foreign key to either B or C, but not both.
本质上,B 类和 C 类都有多个 D 类。但是一个特定的 D 类只属于其中一个。
【问题讨论】:
-
您能解释一下为什么需要继承吗?
-
有一个相关的问题有一些不错的答案可能会有所帮助:stackoverflow.com/questions/1114767/…
标签: python django inheritance django-models foreign-keys