我想完成以下事项: 我有三个派生自抽象类的类:
class Person(models.Model):
name = models.CharField()
...
class Meta:
abstract = True
class TypA(Person):
...
class TypB(Person):
...
class TypC(Person):
...
在另一个课程中,我想将TypA和TypB作为外键引用,如下所示:
class Project(models.Model):
worker = models.ForeignKey(TypA or TypB)
由于无法将两个不同的模型声明为外键,因此我正在寻找解决方案。 我读到了通用外键;但我不确定如何将其应用到我的模型中。
另一个想法是对ForeignKeys使用limit_choices_to
声明。
worker = models.ForeignKey(Person, limit_choices_to={??})
但这似乎是不可能的:
Field defines a relation with model 'Person', which is either not installed, or is abstract.
提前感谢您的帮助。
答案 0 :(得分:0)
Django ForeignKey
字段转换为数据库外键。您的Person
模型是抽象的,因此数据库中不存在该模型,因此该模型不存在外键。
同样,数据库外键只能引用一个表,而不能引用两个表。
如果你真的想要一种灵活的关系到一种以上的表格,我唯一可能看到的是Django的contenttypes framework。
您还希望限制可以指出的模型种类。为此,您最好查看How can I restrict Django's GenericForeignKey to a list of models?示例。
答案 1 :(得分:0)
你只需要引用你的抽象类(比如JAVA):
class Project(models.Model):
worker = models.ForeignKey(Person)
#in your code:
worker = TypeA()
worker.save()
proj = Project()
proj.worker = worker
proj.save()