0

I want to accomplish the following: I have three classes derived from an abstract class:

class Person(models.Model):
  name = models.CharField()
  ...
  class Meta:
    abstract = True

class TypA(Person):
  ...

class TypB(Person):
  ...

class TypC(Person):
  ...

In another class I would like to reference TypA and TypB as a Foreign Key, something like this:

class Project(models.Model):
  worker = models.ForeignKey(TypA or TypB)

Since it is not possible to declare two different models as a Foreign Key I am on the look for solutions. I read about Generic Foreign Keys; but I am unsure how to apply that to my model.

Another idea is to use the limit_choices_to declaration for ForeignKeys.

worker = models.ForeignKey(Person, limit_choices_to={??})

But this is not possible as it seems:

Field defines a relation with model 'Person', which is either not installed, or is abstract.

Thank you in advance for the help.

4

2 回答 2

0

您只需要引用您的抽象类(如 JAVA):

class Project(models.Model):
    worker = models.ForeignKey(Person)


#in your code:
worker = TypeA()
worker.save()
proj = Project()
proj.worker = worker
proj.save()
于 2014-03-28T13:51:34.833 回答
0

DjangoForeignKey字段转换为数据库外键。您的Person模型是抽象的,因此数据库中不存在模型,因此该模型没有外键。

同样,一个数据库外键只能引用一个表,而不是两个。

如果您真的想要与不止一种表的灵活关系,我看到的唯一可能性是 Django 的contenttypes 框架

您还想限制可以指向的模型类型。为此,您最好看看如何将 Django 的 GenericForeignKey 限制为模型列表?例如。

于 2014-03-28T09:52:35.707 回答