如何在 Django 中拥有同一个模型的两个外键? [英] How can I have two foreign keys to the same model in Django?
问题描述
我想对同一个模型有两个外键:
I want to have two foreign keys to the same model:
class Test(models.model):
example1 = models.ForeignKey(Example)
example2 = models.ForeignKey(Example)
我收到如下错误:
字段example1"的访问器与相关的冲突字段'Example.test_set'.添加一个 related_name 参数'example1'的定义.
Accessor for field 'example1' clashes with related field 'Example.test_set'. Add a related_name argument to the definition for 'example1'.
推荐答案
Django 使用一些 python 魔法来定义模型之间的关系,其中一些涉及在关系中使用模型的名称(这就是 'test' in 'test__set' 来自.)我猜,发生的事情是它试图将test__set"两次放入示例模型中,一次是为您定义的每个外键.
Django uses some python magic to define relationships between models, some of which involves using the name of the models in the relationships (that's where the 'test' in 'test__set' is coming from.) What's happening, I would guess, is that it's trying to put "test__set" in the Example model twice, once for each foreign key you've got defined.
错误消息建议尝试:定义一个 related_name
参数(覆盖其中一个test_set"),它可以使用它而不是自动生成两个冲突的名称.
The error message suggests something to try: define a related_name
argument (overriding one of those 'test_set's) that it can use instead of auto-generating two clashing names.
更多信息这里:页面已被删除
More info here: page has been removed
与模型关系相关的当前页面:https://docs.djangoproject.com/en/2.0/ref/models/fields/#module-django.db.models.fields.related
Current page relating to model relationships: https://docs.djangoproject.com/en/2.0/ref/models/fields/#module-django.db.models.fields.related
这篇关于如何在 Django 中拥有同一个模型的两个外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!