79

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?

0

1 Answer 1

113

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?

3
  • 8
    Is there a way to disable reversing?
    – Fomalhaut
    Jan 11, 2017 at 16:09
  • 25
    Yes, related_name='+'
    – Andee
    Jan 11, 2017 at 16:16
  • 1
    setting related names solves the problem in django 4
    – DragonFire
    Aug 15, 2022 at 0:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.