需求
朋友关系,需要M2M自身,代码如下:
class Person(models.Model):
friends=(models.ManyToManyField("self", symmetrical=False)
说明
官方明确的说了, 只有当M2M引用self时,symmetrical才起作用。用来标注是否创建反向关系数据。之前没有碰到过这种需求,就不知道这么个参数。
今天碰到了就做个记录。
官方原始说明:
Only used in the definition of ManyToManyFields on self. Consider the following model:
from django.db import models class Person(models.Model): friends = models.ManyToManyField("self")When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesn’t add a person_set attribute to the Person class. Instead, the ManyToManyField 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, set symmetrical to False. This will force Django to add the descriptor for the reverse relationship, allowing ManyToManyField relationships to be non-symmetrical.
本文详细解析了Django中M2M字段的symmetrical参数,解释了其在自引用场景下的作用,即控制多对多关系是否为对称。通过对Person模型的示例,阐述了设置symmetrical为False时,如何实现非对称的多对多关系。
635

被折叠的 条评论
为什么被折叠?



