需求
朋友关系,需要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.