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)

一对多

posted @ 2019-08-18 14:10  『侠客行』  阅读(572)  评论(0编辑  收藏  举报