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 QuerySet
from readings.models import Book
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 raises(fn,exception):
try:
fn()
except exception:
return True
return False
def run():
assert not Book.objects.exists(), "Use a fresh migrated practice database."
manager=Book.objects
rows=[
("Harbor Atlas","12.50","North","2023-10-01"),
("python Tides","20.00","North","2024-10-07"),
("Python Handbook","20.00","South","2024-04-01"),
("Shore Atlas","30.00","South","2025-01-08"),
("Pilot Notes","45.00","Bay","2025-10-01"),
]
books=[]
for i,(title,price,publisher,day) in enumerate(rows):
data=dict(title=title,price=Decimal(price),publisher=publisher,published_on=date.fromisoformat(day))
if i==0:
obj=Book(**data)
before=[obj.pk,manager.count()]
returned=obj.save()
else:
obj=manager.create(**data)
books.append(obj)
atlas,tides,handbook,shore,pilot=books
qs=manager.order_by("pk")
titles=lambda items:list(items.values_list("title",flat=True))
labels=[row[0] for row in rows]
projected=qs.values("pk","price").first()
tuple_row=qs.values_list("price","publisher").first()
positive={key:titles(qs.filter(**value)) for key,value in {
"in":{"price__in":[20,45]},"gt":{"price__gt":20},"gte":{"price__gte":20},
"lt":{"price__lt":30},"lte":{"price__lte":30},"range":{"price__range":(20,30)}}.items()}
text_date={key:titles(qs.filter(**value)) for key,value in {
"contains":{"title__contains":"Atlas"},"icontains":{"title__icontains":"PYTHON"},
"startswith":{"title__startswith":"Harbor"},"endswith":{"title__endswith":"Atlas"},
"year":{"published_on__year":2024},"month":{"published_on__month":10},"day":{"published_on__day":1}}.items()}
absent=qs.filter(price=0)
stable_price=qs.order_by("price","pk")
results=[
check("Book model, migration and table mapping","Inspect migrated table, explicit primary key and typed fields",
["readings.Book","readings.0001_initial"],[True,"AutoField",32,5,2,"DateField"],
["readings_book" in connection.introspection.table_names(),Book._meta.pk.get_internal_type(),
Book._meta.get_field("title").max_length,Book._meta.get_field("price").max_digits,
Book._meta.get_field("price").decimal_places,Book._meta.get_field("published_on").get_internal_type()]),
check("Instantiate and save, then use Manager.create","Compare unsaved object, save result, created records and read-back values",
rows,[[None,0],None,True,True,5,"12.50","2023-10-01"],
[before,returned,atlas.pk is not None,isinstance(tides,Book),manager.count(),
str(manager.get(pk=atlas.pk).price),manager.get(pk=atlas.pk).published_on.isoformat()]),
check("All, filter, exclude and get branches","Compare model results, primary key, combined predicates, negation and exceptions",
["price=20","publisher=North","missing primary key"],
[True,True,labels,["Harbor Atlas"],["python Tides"],labels[1:],
["Harbor Atlas","Python Handbook","Shore Atlas","Pilot Notes"],"Harbor Atlas",True,True],
[isinstance(manager.all(),QuerySet),isinstance(qs[0],Book),titles(qs),titles(qs.filter(pk=atlas.pk)),
titles(qs.filter(publisher="North",price=20)),titles(qs.exclude(pk=atlas.pk)),
titles(qs.exclude(publisher="North",price=20)),manager.get(pk=atlas.pk).title,
raises(lambda:manager.get(pk=0),Book.DoesNotExist),raises(lambda:manager.get(price=20),Book.MultipleObjectsReturned)]),
check("Ordering, reverse, first, last, count and exists","Compare stable ascending and descending, bounds, scalar and boolean results",
["price","-price","price=0","price=20"],
[labels,labels[::-1],labels,5,2,"Harbor Atlas","Pilot Notes",None,None,True,True,True,False,True,True],
[titles(stable_price),titles(qs.order_by("-price","-pk")),titles(qs.order_by("-price","-pk").reverse()),
manager.count(),qs.filter(price=20).count(),qs.first().title,qs.last().title,absent.first(),absent.last(),
raises(lambda:absent[0],IndexError),raises(lambda:qs[-1],ValueError),qs.exists(),absent.exists(),
raises(lambda:manager.count().exists(),AttributeError),raises(lambda:qs.first().exists(),AttributeError)]),
check("Values, values_list and distinct","Compare dict, tuple, one-field scalar and deduplicated publisher projection",
["pk","price","publisher"],[["pk","price"],atlas.pk,"Decimal","12.50",True,["12.50","North"],
["Bay","North","South"],5],
[list(projected),projected["pk"],type(projected["price"]).__name__,str(projected["price"]),
isinstance(tuple_row,tuple),[str(tuple_row[0]),tuple_row[1]],
sorted(qs.order_by().values_list("publisher",flat=True).distinct()),manager.distinct().count()]),
check("Numeric lookups, membership and inclusive range","Evaluate six numeric lookups and negated membership",
[[20,45],20,30,[20,30]],[
{"in":["python Tides","Python Handbook","Pilot Notes"],"gt":["Shore Atlas","Pilot Notes"],
"gte":labels[1:],"lt":labels[:3],"lte":labels[:4],"range":labels[1:4]},["Harbor Atlas","Shore Atlas"]],
[positive,titles(qs.exclude(price__in=[20,45]))]),
check("Text lookups and date components","Run literal text, case-insensitive text and seven date/text lookups",
["Atlas","PYTHON","Harbor",2024,10,1],
{"contains":["Harbor Atlas","Shore Atlas"],"icontains":["python Tides","Python Handbook"],
"startswith":["Harbor Atlas"],"endswith":["Harbor Atlas","Shore Atlas"],
"year":["python Tides","Python Handbook"],"month":["Harbor Atlas","python Tides","Pilot Notes"],
"day":["Harbor Atlas","Python Handbook","Pilot Notes"]},text_date),
]
with transaction.atomic():
single=manager.get(pk=pilot.pk).delete()
chosen=manager.filter(pk__in=[tides.pk,handbook.pk]).delete()
rest=manager.all().delete()
deleted=[list(single),list(chosen),list(rest),manager.count(),raises(manager.delete if hasattr(manager,"delete") else
lambda:getattr(manager,"delete"),AttributeError)]
transaction.set_rollback(True)
results.append(check("Instance deletion, QuerySet deletion and Manager boundary","Delete individual, selected, and remaining rows within rollback",
[pilot.pk,[tides.pk,handbook.pk],"all"],
[[1,{"readings.Book":1}],[2,{"readings.Book":2}],[2,{"readings.Book":2}],0,True,5],deleted+[manager.count()]))
atlas.price=Decimal("14.50")
result=atlas.save(update_fields=["price"])
touched=manager.filter(pk__in=[tides.pk,handbook.pk]).update(price=Decimal("22.75"))
prices=[str(v) for v in manager.order_by("pk").values_list("price",flat=True)]
results.append(check("Instance save return and QuerySet.update count","Save one row, update two in a single query and read persisted prices",
["14.50","22.75"],[None,2,["14.50","22.75","22.75","30.00","45.00"]],[result,touched,prices]))
return results
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-orm-single/query_exercise.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
query_exercise.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14、Django 5.2.19、SQLite、Edge。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a164.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a176.zip