如何在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'冲突。在example1的定义中添加一个related_name参数
。
Accessor for field 'example1' clashes with related field 'Example.test_set'. Add a related_name argument to the definition for 'example1'.
推荐答案
Django使用一些python魔术来定义模型之间的关系,其中一些涉及使用关系中的模型名称(这是test__set中的'test'来自哪里)。我猜想,正在发生的事情是,它正在尝试将示例模型中的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 autogenerating two clashing names.
更多信息 here
这篇关于如何在Django中使用同一型号的两个外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!