Django:外键冲突的反向访问器

问题:Django:外键冲突的反向访问器

我有两个从基类继承的Django模型:

- Request
    - Inquiry
    - Analysis

请求具有两个内置用户模型的外键。

create_user = models.ForeignKey(User, related_name='requests_created')
assign_user = models.ForeignKey(User, related_name='requests_assigned')

由于某种原因,我遇到了错误

Reverse accessor for 'Analysis.assign_user' clashes with reverse accessor for 'Inquiry.assign_user'.

我读过的所有内容都说设置related_name应当可以防止冲突,但是我仍然遇到相同的错误。谁能想到为什么会这样?谢谢!

I have two Django models which inherit from a base class:

- Request
    - Inquiry
    - Analysis

Request has two foreign keys to the built-in User model.

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'.

Everything I’ve read says that setting the related_name should prevent the clash, but I’m still getting the same error. Can anyone think of why this would be happening? Thanks!


回答 0

这样related_name可以确保各个字段之间不会发生冲突,但是您有两个模型,每个模型都具有这两个字段。您需要在每个模型中放置具体模型的名称,您可以使用一些特殊的字符串替换来做到这一点:

 create_user = models.ForeignKey(User, related_name='%(class)s_requests_created')

The related_name would 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:

 create_user = models.ForeignKey(User, related_name='%(class)s_requests_created')