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")

