用 Django 聚合、分组与 F/Q 表达式统计书目
区分聚合字典与查询集分组,逐项验证价格与作者统计、F 字段运算及 Q 条件组合。
学完这一章,你能够
- 区分聚合字典与查询集分组,逐项验证价格与作者统计、F 字段运算及 Q 条件组合。
先检查聚合结果的形状
从 django.db.models 导入 Avg、Max、Min、Count、Sum。aggregate 立即执行并返回字典,可以取结果但不能再接 QuerySet.filter。Avg('price') 默认键是 price__avg,也可以通过关键字参数给输出命名。
四条书目的平均价 50.00,合计 200.00,最高 100.00,最低 20.00。Count('id') 为 4。日期字段用 Min 和 Max 找最早和最晚日期。空结果 Count 为 0,Min 为 None,Sum 可用 default 指定 0。
分组键取决于 values 与 annotate 的先后
项目在同一个数据库准备书目、出版组和作者,也准备含文本部门的 Shift、含 Department 外键的 AssignedShift。两种班组方案均按部门聚合,结果分别为 70.00 和 60.00。
values('name') 再 annotate(Min(...)) 按名称分组。反过来,先 annotate 再 values_list 仍按模型行维度计算,最后一步仅投影字段,必须明确包含别名。本站添加一条同名出版组后核对合并的一行与分开的两行,并回滚。
values 返回字典行,values_list 返回元组行,两者仍是 QuerySet。切片限制结果,本站实际捕获 LIMIT 2。聚合后排序时可用别名并添加稳定的并列排序键。
分别验证出版组和作者统计
每个出版组以 Min('book__price') 取最便宜书目,Empty Press 没有书时得到 None。每本书的作者数由 Count 统计,四本书得到 2、1、1、0。
先 filter(title__startswith='Harbor') 再计数,得到一本书与两个作者。筛选计数大于 0 意味着至少一个作者,大于 1 才是多位作者。本站对照两种条件。
按作者数降序,并用书名稳定处理并列。作者视角用 Sum('book__price') 汇总其书目价格。Mira 为 50.00,Jin 为 70.00,没有书目的 Tao 得到 None。
让数据库计算 F 表达式
F('age') 引用同一行的年龄,pay__gt=F('age') 找到报酬数值高于年龄数值的两条示例记录。这里用不同字段演示比较,不赋予数值相同的业务单位。
数据库可执行 F 与常量或其他字段的加、减、乘、除和取余。本站验证五种运算,并用 update(price=F('price')+Decimal('5.00')) 在单条 UPDATE 中改四行。读取新价格后回滚。
用 Q 显式组合条件
Q 可以用 &、|、~ 组合,优先级从高到低为 ~、&、|。业务谓词建议显式加括号。本站验证价格大于 60 或书名以 Harbor 开头。
把日期的年与月用 & 结合,再对整体取反,可表达排除某个月。本站将它与书名 Atlas 后缀的条件作或组合。
Q 对象放在关键字条件之前,两者以 AND 合并。本例查 2023 或 2024 出版且书名含 a 的书。不同后端对文本比较的规则可能不同。
查看真实分组报告
浏览器从关联页切到统计页,读取每组最低价格与按作者数排序的名单,再切回关联页。截图记录的是当前 SQLite 计算结果。

实际运行聚合、分组、F 和 Q
import json
import os
from datetime import date
from decimal import Decimal
os.environ.setdefault("DJANGO_SETTINGS_MODULE","settings")
import django
django.setup()
from django.db import connection,transaction
from django.db.models import Avg,Count,F,Max,Min,Q,QuerySet,Sum
from django.test.utils import CaptureQueriesContext
from readings.models import AssignedShift,Author,Book,Publisher,Shift
from seed import seed
def check(name,operation,inputs,expected,actual):
assert expected==actual,(name,expected,actual)
return dict(name=name,operation=operation,input=inputs,expected=expected,actual=actual)
def money(value):
return None if value is None else str(value.quantize(Decimal("0.01")))
def run():
if not Book.objects.exists():
seed()
books=Book.objects.order_by("pk")
avg=books.aggregate(Avg("price"))
details=books.aggregate(n=Count("id"),high=Max("price"),low=Min("price"),total=Sum("price"),
first=Min("published_on"),last=Max("published_on"))
empty=books.none().aggregate(n=Count("id"),low=Min("price"),total=Sum("price",default=Decimal("0.00")))
totals=check("Aggregate terminal results and empty input",
"Evaluate actual aggregate dictionary with default key, explicit aliases, date bounds and empty input",
["price","published_on","empty QuerySet"],
[True,["price__avg"],"50.00",4,"100.00","20.00","200.00","2023-10-10","2025-05-20",0,None,"0.00",False],
[isinstance(avg,dict),list(avg),money(avg["price__avg"]),details["n"],money(details["high"]),
money(details["low"]),money(details["total"]),details["first"].isoformat(),details["last"].isoformat(),
empty["n"],empty["low"],money(empty["total"]),hasattr(avg,"filter")])
publishers=Publisher.objects.values("name").annotate(low=Min("book__price")).order_by("name")
pub_rows=[(row["name"],money(row["low"])) for row in publishers]
annotated=books.annotate(authors_total=Count("authors__name"))
author_rows=list(annotated.values_list("title","authors_total"))
prefixed=list(books.filter(title__startswith="Harbor").annotate(total=Count("authors")).values("title","total"))
at_least_one=list(annotated.filter(authors_total__gt=0).values_list("title",flat=True))
multiple=list(annotated.filter(authors_total__gt=1).values_list("title",flat=True))
with CaptureQueriesContext(connection) as sql:
top=list(annotated.order_by("-authors_total","title")[:2].values_list("title","authors_total"))
all_ranked=list(annotated.order_by("-authors_total","title").values_list("title","authors_total"))
income=[(name,money(value)) for name,value in Author.objects.annotate(total=Sum("book__price")).order_by("name").values_list("name","total")]
units=[(key,money(total)) for key,total in Shift.objects.values("unit").annotate(total=Sum("pay")).order_by("unit").values_list("unit","total")]
joined=[(key,money(total)) for key,total in AssignedShift.objects.values("unit__title").annotate(total=Sum("pay")).order_by("unit__title").values_list("unit__title","total")]
with transaction.atomic():
duplicate=Publisher.objects.create(name="North Press",city="Other Bay",email="other@example.invalid")
Book.objects.create(title="Duplicate group test",price=Decimal("5.00"),published_on=date(2025,9,1),publisher=duplicate)
values_first=[money(row["low"]) for row in Publisher.objects.filter(name="North Press").values("name").annotate(low=Min("book__price"))]
annotate_first=[money(low) for low in Publisher.objects.filter(name="North Press").annotate(low=Min("book__price")).order_by("pk").values_list("low",flat=True)]
transaction.set_rollback(True)
grouping=check("Grouping, projections, count filters and related totals",
"Run publisher minimums, author count branches, SQL slicing, totals and a duplicate-name grouping experiment",
["publishers","Harbor prefix",">0",">1","top two","duplicate North Press"],
[True,True,[("Empty Press",None),("North Press","20.00"),("South Press","50.00")],
[("Harbor Signals",2),("Coastal Atlas",1),("Soundings",1),("Empty Log",0)],
[{"title":"Harbor Signals","total":2}],["Harbor Signals","Coastal Atlas","Soundings"],["Harbor Signals"],
[("Harbor Signals",2),("Coastal Atlas",1)],True,
[("Harbor Signals",2),("Coastal Atlas",1),("Soundings",1),("Empty Log",0)],
[("Jin","70.00"),("Mira","50.00"),("Tao",None)],
[("Observing","70.00"),("Survey","60.00")],[("Observing","70.00"),("Survey","60.00")],["5.00"],["20.00","5.00"]],
[isinstance(publishers,QuerySet),isinstance(annotated.values_list("title","authors_total"),QuerySet),
pub_rows,author_rows,prefixed,at_least_one,multiple,top,"LIMIT 2" in sql[0]["sql"],all_ranked,income,units,joined,values_first,annotate_first])
compared=list(Shift.objects.filter(pay__gt=F("age")).order_by("name").values_list("name","age"))
lee=Shift.objects.annotate(plus=F("pay")+2,minus=F("pay")-F("age"),times=F("pay")*2,
divided=F("pay")/2,mod=F("age")%5).values_list("plus","minus","times","divided","mod").get(name="Lee")
with transaction.atomic():
with CaptureQueriesContext(connection) as queries:
changed=Book.objects.update(price=F("price")+Decimal("5.00"))
shifted=[money(v) for v in books.values_list("price",flat=True)]
transaction.set_rollback(True)
arithmetic=check("F field comparison and in-database arithmetic",
"Compare fields, evaluate five operators and update prices via F in one SQL statement before rollback",
["pay > age","Lee","price + 5.00"],
[[("Lee",24),("Paz",25)],["42.00","16.00","80.00","20.00",4],4,1,True,
["25.00","35.00","55.00","105.00"],["20.00","30.00","50.00","100.00"]],
[compared,[*[money(value) for value in lee[:4]],lee[4]],changed,len(queries),
queries[0]["sql"].lstrip().upper().startswith("UPDATE") and "+" in queries[0]["sql"],
shifted,[money(v) for v in books.values_list("price",flat=True)]])
either=[(title,money(price)) for title,price in books.filter(Q(price__gt=60)|Q(title__startswith="Harbor")).values_list("title","price")]
excluded=list(books.filter(Q(title__endswith="Atlas")|~(Q(published_on__year=2024)&Q(published_on__month=10))).values_list("title",flat=True))
mixed=list(books.filter(Q(published_on__year=2023)|Q(published_on__year=2024),title__contains="a").values_list("title",flat=True))
precedence=list(books.filter(Q(title__startswith="Harbor")|Q(price__gt=40)&~Q(title__endswith="Log")).values_list("title",flat=True))
logic=check("Q OR, AND, NOT and mixed keywords","Run three combined predicates and one operator-precedence example",
["price>60 OR Harbor","Atlas OR NOT October 2024","(2023 OR 2024) AND contains a","~ before & before |"],
[[("Harbor Signals","20.00"),("Empty Log","100.00")],["Harbor Signals","Coastal Atlas","Empty Log"],
["Harbor Signals","Coastal Atlas"],["Harbor Signals","Soundings"]],[either,excluded,mixed,precedence])
return [totals,grouping,arithmetic,logic]
if __name__=="__main__":
print(json.dumps(run(),ensure_ascii=False))
- 聚合返回字典,分组仍是 QuerySet。边界过滤区分至少一个作者与多个作者,更新回滚后原价格恢复。
所需环境:CPython 3.12.14、Django 5.2.19、SQLite、Edge
当前源码 SHA256:56310904dbc8856772732019a9d0f9850cb3886aafcd1642a78f143ae803ecb8
完整开发工程
解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。
所需环境:CPython 3.12.14、Django 5.2.19、SQLite、Edge
ZIP SHA256:e0cdc0d67d3b50d7f807b30a652dc0f84141049cc5dd429e3c8d05f3b25d11f2
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
执行聚合练习,分别比较 >0 和 >1,并查看同名组实验。
展开参考解答
检查空组、并列、分组顺序和更新回滚,再在本机统计页查看真实数据。