Django ORM (四) annotate,F,Q 查询
annotate
可以通过计算查询结果中每一个对象所关联的对象集合,从而得出总计值(也可以是平均值或总和),即为查询集的每一项生成聚合。
from django.shortcuts import render, HttpResponse
from app01 import models
from app01.models import Book,Author,Publisher
from django.db.models import Avg,Min,Sum,Max
def data_oper(req):
# 查询每个出版社书的总价
obj = models.Book.objects.values("publisher__name").annotate(Sum("price"))
print(obj)
return HttpResponse("Hello world")
# 查询 klvchen 出的书总价格
...
def data_oper(req):
obj = Book.objects.filter(authors__name="klvchen").aggregate(Sum("price"))
print(obj)
return HttpResponse("Hello world")
F查询
F 使用查询条件的值,专门取对象中某列值的操作
from django.shortcuts import render, HttpResponse
from app01 import models
from app01.models import Book,Author,Publisher
from django.db.models import Avg,Min,Sum,Max
from django.db.models import F
# 书籍的价格都加20
def data_oper(req):
models.Book.objects.all().update(price=F("price")+20)
return HttpResponse("Hello world")
Q 查询
Q 构建搜索条件
from django.shortcuts import render, HttpResponse
from app01 import models
from app01.models import Book,Author,Publisher
from django.db.models import Avg,Min,Sum,Max
from django.db.models import F,Q
from django.db.models import F,Q
# 查询 book 表 id 为3的书名,这里书名是因为在 models.py 定义的 class Book 里面 __str__ 返回的是 title 字段
def data_oper(req):
obj = models.Book.objects.filter(Q(id=3))[0]
print(obj)
return HttpResponse("Hello world")
.....
from django.db.models import F,Q
# 查询 book 表 id为3或者 title 为 GO 的记录
def data_oper(req):
obj = models.Book.objects.filter(Q(id=3)|Q(title="GO"))
print(obj)
return HttpResponse("Hello world")
Q对象可以与关键字参数查询一起使用,不过一定要把Q对象放在关键字参数查询的前面
from django.db.models import F,Q
def data_oper(req):
obj = models.Book.objects.filter(Q(price__gt=50)&(Q(id=3)|Q(title="php")), publisher_id=1)
print(obj)
return HttpResponse("Hello world")