Django的自关联
Django的自关联
多对多关联
models.py
#### 自关联
class User(models.Model):
name = models.CharField(max_length=32)
gender_list = [
(1,'男'),
(2,'女')
]
gender = models.IntegerField(choices=gender_list, default=1)
m = models.ManyToManyField('User') #关联自己
views.py:
#### 查询和zekai约会的姑娘
res = models.User.objects.filter(name='zekai', gender=1).first()
#print(res) ### obj
objs = res.m.all()
'''
1. select * from app01_user_m where from_user_id = 1 ### to_user_id=[3,4]
2. select * from app01_user where id in (3,4)
'''
for obj in objs:
print(obj.name)
#### 查询和cuihua约会的男生
res = models.User.objects.filter(name='cuihua', gender=2).first()
objs = res.user_set.all()
'''
1. select * from app01_user_m where to_user_id = 3 ### from_user_id=[1,2]
2. select * from app01_user where id in (1,2)
'''
for obj in objs:
print(obj.name)
一对多
![微信](https://www.cnblogs.com/images/cnblogs_com/bladecheng/1492360/o_weinxin.png)
![QQ](https://www.cnblogs.com/images/cnblogs_com/bladecheng/1492360/o_qrcode_1561712740560.jpg)
个性签名:独学而无友,则孤陋而寡闻!
如果觉得这篇文章对你有小小的帮助的话,记得点个“关注”哦,博主在此感谢!还可以扫码添加好友,交流编程上的问题哦!
万水千山总是情,点赞再走行不行!哈哈哈(っ•̀ω•́)っ✎⁾⁾!