Fix Python – Django: reverse accessors for foreign keys clashing


Asked By – serverpunk

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!

Now we will see solution for issue: Django: reverse accessors for foreign keys clashing


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

This question is answered By – Daniel Roseman

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0