Django反向访问冲突

我正在尝试迁移这两个模型:

 

 

# 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中建立多对多的关系.为什么我的代码错了?我该如何解决?

 
代码是错误的,因为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作为人的对象相关.

 

 

posted @ 2019-09-06 16:48  追赶菜鸟  阅读(376)  评论(0编辑  收藏  举报