我读了这个问题线程( Difference between ManyToOneRel and ForeignKey? ),但我没有完全理解它。我需要多对一的关系,以便我可以添加以下功能。尝试了多对多,这使得两个用户互相关注,即使其中一个用户不想关注(如果一个用户点击“关注”,那么它的行为就像另一个用户也做了同样的事情一样。)
问题是,我是否需要为关注者(关注登录用户的人)使用 ManyToOneRel 字段,并为用户关注的人使用相同的字段?
请原谅,我正在自学一切,有些东西有时可能很难掌握。
最佳答案
您需要通过设置 symmetrical=...
parameter [Django-doc] 使关系不对称为 False
,例如:
class Profile(models.Model):
follows = models.ManyToManyField(
'self',
<b>symmetrical=False</b>,
related_name='followers'
)
正如文档所述:
When Django processes this model, it identifies that it has a
ManyToManyField
on itself, and as a result, it doesn’t add aperson_set
attribute to the Person class. Instead, theManyToManyField
is assumed to be symmetrical – that is, if I am your friend, then you are my friend.If you do not want symmetry in many-to-many relationships with
self
, setsymmetrical
toFalse
. This will force Django to add the descriptor for the reverse relationship, allowingManyToManyField
relationships to be non-symmetrical.
关于django - ManyToOneRel 字段用于以下功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57295504/