# 1.查询jack的手机号和作者姓名
res = models.Author.objects.filter(name='jack').values('author_detail__phone','name')print(res)# 反向
res = models.AuthorDetail.objects.filter(author__name='jack')# 拿作者姓名是jack的作者详情
res = models.AuthorDetail.objects.filter(author__name='jack').values('phone','author__name')print(res)# 2.查询书籍主键为1的出版社名称和书的名称
res = models.Book.objects.filter(pk=1).values('title','publish__name')print(res)# 反向
res = models.Publish.objects.filter(book__id=1).values('name','book__title')print(res)# 3.查询书籍主键为1的作者姓名
res = models.Book.objects.filter(pk=1).values('authors__name')print(res)# 反向
res = models.Author.objects.filter(book__id=1).values('name')print(res)# 查询书籍主键是1的作者的手机号# book author authordetail
res = models.Book.objects.filter(pk=1).values('authors__author_detail__phone')print(res)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
10. 聚合查询
# 聚合查询 aggregate"""
聚合查询通常情况下都是配合分组一起使用的
"""from app01 import models
from django.db.models import Max,Min,Sum,Count,Avg
# 1 所有书的平均价格
res = models.Book.objects.aggregate(Avg('price'))print(res)# 2.上述方法一次性使用
res = models.Book.objects.aggregate(Max('price'),Min('price'),Sum('price'),Count('pk'),Avg('price'))print(res)
only与defer
select_related与prefetch_related
"""
orm语句的特点:
惰性查询
如果你仅仅只是书写了orm语句 在后面根本没有用到该语句所查询出来的结果
那么orm会自动识别 直接不执行
"""
res = models.Book.objects.all()print(res)# 要用数据了才会走数据库# only与defer# 想要获取书籍表中所有数的名字
res = models.Book.objects.values('title')for d in res:print(d.get('title'))# 实现获取到的是一个数据对象 然后点title就能够拿到书名 并且没有其他字段
res = models.Book.objects.only('title')
res = models.Book.objects.all()print(res)# , , , , ]>for i in res:print(i.title)# 点击only括号内的字段 不会走数据库print(i.price)# 点击only括号内没有的字段 会重新走数据库查询而all不需要走数据库了
res = models.Book.objects.defer('title')# 对象除了没有title属性之外其他的都有for i in res:print(i.price)"""
defer与only刚好相反
defer括号内放的字段不在查询出来的对象里面 查询该字段需要重新走数据
而如果查询的是非括号内的字段 则不需要走数据库了
"""# select_related与prefetch_related 跟跨表操作有关
res = models.Book.objects.all()for i in res:print(i.publish.name)# 每循环一次就要走一次数据库查询# 优化
res = models.Book.objects.select_related('authors')# INNER JOIN"""
select_related内部直接先将book与publish连起来 然后一次性将大表里面的所有数据
全部封装给查询出来的对象
这个时候对象无论是获取book表的数据还是publish的数据都无需再走数据库查询了
注意事项:
select_related括号内只能放外键字段 一对多 一对一
多对多不行
"""# for i in res:# print(i.publish.name) # 每循环一次就要走一次数据库查询
res = models.Book.objects.prefetch_related('publish')# 子查询"""
prefetch_related该方法内部其实就是子查询
将子查询查询出来的所有结果也给你封装到对象中
给你的感觉好像也是一次性搞定的
"""for i in res:print(i.publish.name)