我正在尝试迁移这两个模型:
# 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)
但我有这个错误:
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'.
我想在模型Person
中建立多对多的关系。为什么我的代码错了?我该如何解决?
答案 0 :(得分:13)
代码错误,因为Person会得到一个反向关系回Person2Person.person,也回到Person2Person.friend;默认名称是Person.person2person_set,但Django不能为两者使用相同的名称。
因此,您可以在其中一个或两个上设置related_name
:
class Person2Person(models.Model):
person = models.ForeignKey(Person, related_name='person2persons')
friend = models.ForeignKey(Person, related_name='friends')
现在Person.friends与Person2Person对象相关,Person2Person对象将此Person作为朋友,Person.person2person与以此Person为人的对象相关。
然而,为什么你没有在Person上使用ManyToManyField到'self'
?