related_name argument not working as expected in Django model?

Question:

I recently got a ForeignKey clash in my Django model. I have the need to have two foreign keys (owner, assigned_to) ultimately pointing to the same model (a user).

From what I understand I need a related_name argument to solve that problem. So I did that:

assigned_to = models.ForeignKey(TaskUser, blank=True, null=True, related_name='user_assignment')

and

owner = models.ForeignKey(TaskUser, related_name="user_ownership"

But I’m still getting an error:

tasks.task: Accessor for field 'owner' clashes with related field 'TaskUser.user
_ownership'. Add a related_name argument to the definition for 'owner'.
tasks.task: Reverse query name for field 'owner' clashes with related field 'TaskUser.user_ownership'. Add a related_name argument to the definition for 'owner'.

Why am I still getting this error?

There is one catch, owner is in a super class (BaseWidget) and assigned_to is in a sub class (Task). Are there issues with using related_name in an inheritance relationship? Do I need to just override the inheritance of owner and redefine related_name in the sub class instead? I’d appreciate any help!

Asked By: Mark Nenadov

||

Answers:

If you are using related_name in abstract base class you need to use a ‘%(app_label)s’ and ‘%(class)s’ in it.
Its mentioned in django doc

Be careful with related_name

Answered By: Aldarund

If you have ForeignKey relationships in an abstract base class every class inheriting from it will have this relationship. As a result of this you must not ‘hardcode’ its related_name, because all sub classes will try to create the same accessor on the realted class (TaskUser in this case).

You should better do something like:

owner = models.ForeignKey(TaskUser, related_name="%(app_label)s_%(class)s_ownership")

See the django docs on this.

Answered By: Bernhard Vallant
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.