django中model的symmetrical参数

本文详细解析了Django中M2M字段的symmetrical参数,解释了其在自引用场景下的作用,即控制多对多关系是否为对称。通过对Person模型的示例,阐述了设置symmetrical为False时,如何实现非对称的多对多关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

M2M中symmetrical参数

需求

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值