如何在一个模型中引用两个外键

0 投票
2 回答
1078 浏览
提问于 2025-04-18 00:18

我想实现以下目标:

我有三个类,它们都是从一个抽象类派生出来的:

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)

但是,似乎不能把两个不同的模型声明为外键,所以我在寻找解决方案。

我读到过关于通用外键的内容,但我不太确定如何把它应用到我的模型中。

另一个想法是使用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.

提前感谢大家的帮助。

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()
0

Django中的ForeignKey字段对应数据库中的外键。你的Person模型是抽象的,这意味着它在数据库中并不存在,所以就不能有指向它的外键。

同样,数据库中的外键只能指向一个表,而不能同时指向两个表。

如果你真的想要一个可以灵活关联多种表的方式,我认为唯一的选择是Django的内容类型框架

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

撰写回答