Python Django:用于外键冲突的反向访问器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22538563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django: reverse accessors for foreign keys clashing
提问by Rob
I have two Django models which inherit from a base class:
我有两个从基类继承的 Django 模型:
- Request
- Inquiry
- Analysis
Request has two foreign keys to the built-in User model.
Request 对内置的 User 模型有两个外键。
create_user = models.ForeignKey(User, related_name='requests_created')
assign_user = models.ForeignKey(User, related_name='requests_assigned')
For some reason I'm getting the error
由于某种原因,我收到错误
Reverse accessor for 'Analysis.assign_user' clashes with reverse accessor for 'Inquiry.assign_user'.
Reverse accessor for 'Analysis.assign_user' clashes with reverse accessor for 'Inquiry.assign_user'.
Everything I've read says that setting the related_nameshould prevent the clash, but I'm still getting the same error. Can anyone think of why this would be happening? Thanks!
我读过的所有内容都说设置related_name应该可以防止冲突,但我仍然遇到相同的错误。谁能想到为什么会发生这种情况?谢谢!
采纳答案by Daniel Roseman
The related_namewould ensure that the fields were not conflicting with each other, but you have two models, each of which has both of those fields. You need to put the name of the concrete model in each one, which you can do with some special string substitution:
这related_name将确保这些字段不会相互冲突,但是您有两个模型,每个模型都有这两个字段。您需要将具体模型的名称放在每个模型中,您可以使用一些特殊的字符串替换来实现:
create_user = models.ForeignKey(User, related_name='%(class)s_requests_created')

