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))
本例需在 CPython 3.12.14、Django 5.2.19、SQLite、Edge 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14、Django 5.2.19、SQLite、Edge
入口文件:projects/django-relations/aggregation_exercise.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
aggregation_exercise.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14、Django 5.2.19、SQLite、Edge。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202612a177.zip
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a164.zip