fields.E304 Reverse accessor clashes in Django

Django

Django Problem Overview


I am trying to migrate these two models:

# models.py

from django.db import models


class Person(models.Model):
    name = models.CharField(max_length=64)


class Person2Person(models.Model):
    person = models.ForeignKey(Person)
    friend = models.ForeignKey(Person)

But I have got this error:

SystemCheckError: System check identified some issues:

ERRORS:
website.Person2Person.friend: (fields.E304) Reverse accessor for 'Person2Person.friend' clashes with reverse accessor for 'Person2Person.person'.
    HINT: Add or change a related_name argument to the definition for 'Person2Person.friend' or 'Person2Person.person'.
website.Person2Person.person: (fields.E304) Reverse accessor for 'Person2Person.person' clashes with reverse accessor for 'Person2Person.friend'.
    HINT: Add or change a related_name argument to the definition for 'Person2Person.person' or 'Person2Person.friend'.

I want to make a relationship many-to-many in the model Person. Why is my code wrong? And how should I fix it?

Django Solutions


Solution 1 - Django

The code is wrong because Person will get a reverse relationship back to Person2Person.person, and also to Person2Person.friend; the default name would be Person.person2person_set but Django can't use the same name for both.

So you could set a related_name on either, or both:

class Person2Person(models.Model):
    person = models.ForeignKey(Person, related_name='person2persons')
    friend = models.ForeignKey(Person, related_name='friends')

Now Person.friend's related to the Person2Person objects that have this Person as a friend, and Person.person2person to the ones that have this Person as a person.

However, why aren't you using a ManyToManyField to 'self' on Person?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFomalhautView Question on Stackoverflow
Solution 1 - DjangoRemcoGerlichView Answer on Stackoverflow