# 1. 返回值QuerySet类型(object对象列表) group_list = models.UserInfo.objects.all() for row in group_list: print(row.id, row.title, row.ug_id) print(row.ug.title) # ug代表UserGroup中的一行,因此这样可以联表操作
# 2. 返回值[{'id':1,'username':},{..}] group_list = models.UserInfo.objects.all().values('id','username','ug__title') for row in group_list: print(row['id'],row[ug__title]) # 在遍历值时就进行跨表操作 # 3. 返回值 [(1,'..','..'),(2,'..','..')] group_list = models.UserInfo.objects.all().values_list('id','username','ug__title') for row in group_list: print(row[0],row[2]) # 在遍历值时就进行跨表操作
条件查找:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
group_list = models.UserGroup.objects.filter(id=1) # where id = 1 group_list = models.UserGroup.objects.filter(id=1,name='xx') # where id = 1 and name=xx group_list = models.UserGroup.objects.filter(id__gt=1) # where id > 1 group_list = models.UserGroup.objects.filter(id__gte=1) # where id >= 1 group_list = models.UserGroup.objects.exclude(id=1) # where id ≠ 1 group_list = models.UserGroup.objects.filter(id__gt=1).first() group_list = models.UserGroup.objects.filter(id__lt=1) # where id < 1 group_list = models.UserGroup.objects.filter(id__in=[1,2,3]) # where id in [1,2,3] group_list = models.UserGroup.objects.filter(id__range=[1,2]) # where 1<=id<=2 group_list = models.UserGroup.objects.filter(name__startswith='xxx') group_list = models.UserGroup.objects.filter(name__contains='xxx') models.UserGroup.objects.all().count() # 数量 models.UserGroup.objects.all()[1:19] # 片选 # 跨表: # 1. 正向 xxx.filter('ug__title'='超级用户').values('id','name','ut__title') # 2. 反向 xxx.filter('表名__title'='超级用户').values('id','name','表名__title')
正反向查找:
1 2 3 4 5 6 7
# 正向寻找:一对一 反向寻找:一对多 for obj in models.UserGroup.objects.all(): for link in obj.userinfo_set.all(): # 反向查找:关联表名小写_set.all() -> object列表 print(link.username, link.ug_id) for obj in models.UserGroup.objects.values('id','title','userinfo'): print(obj)
con = Q() con.add(q1, 'AND') con.add(q2, 'AND') models.Tb1.objects.filter(con) ## 相当于 (id=1 or id=10) and (c1=1 or c1=10)
extra(额外的查询条件以及相关表、排序等)
1 2 3 4 5
extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None) Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,)) Entry.objects.extra(where=['headline=%s'], params=['Lennon']) Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"]) Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])
原生SQL语句
1 2 3 4
from django.db import connection, connections cursor = connection.cursor() # cursor = connections['default'].cursor() cursor.execute("""SELECT * from auth_user where id = %s""", [1]) row = cursor.fetchone()