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 IntegrityError,connection,transaction
from readings.models import Author,Book,Draft,Profile,Publisher
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 rejected(work,exception):
try:
with transaction.atomic():
work()
except exception:
return True
return False
def run():
north,south,empty,mira,jin,tao,harbor,atlas,sound,unused=seed()
tables=connection.introspection.table_names()
with connection.cursor() as cursor:
profile_constraints=connection.introspection.get_constraints(cursor,"readings_author")
keys=[item["foreign_key"] for item in profile_constraints.values() if item["columns"]==["profile_id"] and item["foreign_key"]]
unique=any(item["unique"] and item["columns"]==["profile_id"] for item in profile_constraints.values())
duplicate=rejected(lambda:Author.objects.create(name="Duplicate",age=19,profile=mira.profile),IntegrityError)
with transaction.atomic(),connection.cursor() as cur:
cur.execute("INSERT INTO readings_publisher(name,city,email) VALUES (%s,%s,%s)",
["Parameter Press","Sandbox","example@example.invalid"])
cur.execute("INSERT INTO readings_profile(visibility,phone,address,birthday) VALUES (%s,%s,%s,%s)",
[1,"010-0400","Test Bay","1990-04-09"])
profile=Profile.objects.get(phone="010-0400")
cur.execute("INSERT INTO readings_author(name,age,profile_id) VALUES (%s,%s,%s)",["Raw Author",26,profile.pk])
raw=["Parameter Press",profile.author.name,profile.get_visibility_display()]
assert Publisher.objects.get(name=raw[0]).city=="Sandbox"
transaction.set_rollback(True)
schema=check("Relation schema and referential integrity",
"Read real constraints, reject reused profile, insert parent rows first with parameterized SQL and roll back",
["publisher","profile","author","book","automatic join table"],
[True,True,[("readings_profile","id")],True,["Parameter Press","Raw Author","组内"],False],
[Book.authors.through._meta.db_table in tables,unique,keys,duplicate,raw,Author.objects.filter(name="Raw Author").exists()])
foreign=[harbor.publisher_id==north.pk,atlas.publisher==north,sound.publisher==south]
with transaction.atomic():
integer_rejected=rejected(lambda:north.book_set.add(sound.pk),TypeError)
missing_parent=rejected(lambda:Book.objects.create(title="Unbound",price=Decimal("1.00"),
published_on=date(2026,1,1),publisher=Publisher(name="Unsaved")),ValueError)
moved=north.book_set.add(sound)
sound.refresh_from_db()
moved_ok=sound.publisher_id==north.pk
draft=Draft.objects.create(title="Coast draft")
first=north.draft_set.add(draft)
north.draft_set.remove(draft)
draft.refresh_from_db()
removed_ok=draft.publisher_id is None
north.draft_set.add(draft)
north.draft_set.clear()
draft.refresh_from_db()
cleared_ok=draft.publisher_id is None
transaction.set_rollback(True)
sound.refresh_from_db()
foreign=check("ForeignKey object, primary key and reverse-manager boundaries",
"Compare FK object and ID; move via reverse manager; reject invalid inputs; remove and clear nullable links",
["saved Publisher","integer","unsaved parent","nullable Draft"],
[[True,True,True],True,True,None,True,None,True,True,False,False,True],
[foreign,integer_rejected,missing_parent,moved,moved_ok,first,removed_ok,cleared_ok,
hasattr(north.book_set,"remove"),hasattr(north.book_set,"clear"),sound.publisher_id==south.pk])
with transaction.atomic():
unsaved=rejected(lambda:Book(title="Unbound").authors.add(mira),ValueError)
add_objects=harbor.authors.add(*Author.objects.filter(name__in=["Mira","Tao"]))
add_ids=harbor.authors.add(*[jin.pk,tao.pk])
full=sorted(harbor.authors.values_list("name",flat=True))
new=jin.book_set.create(title="Fog Watch",price=Decimal("23.00"),published_on=date(2026,1,2),publisher=south)
removal=tao.book_set.remove(harbor)
removed=not harbor.authors.filter(pk=tao.pk).exists()
clearing=harbor.authors.clear()
cleared=[harbor.authors.count(),Author.objects.count(),Book.objects.filter(pk=harbor.pk).exists()]
transaction.set_rollback(True)
m2m=check("Many-to-many add, create, remove and clear",
"Exercise objects and IDs, reverse create and remove, duplicate add and clear without deleting endpoints",
["harbor","authors","Fog Watch"],
[True,None,None,["Jin","Mira","Tao"],"Fog Watch",None,True,None,[0,3,True],False],
[unsaved,add_objects,add_ids,full,new.title,removal,removed,clearing,cleared,Book.objects.filter(title="Fog Watch").exists()])
object_case=check("Traverse relationships with model instances",
"Read forward and reverse FK, one-to-one, and many-to-many accessors",
["Harbor Signals","North Press","Mira","Jin"],
["Bay City",["Harbor Signals","Coastal Atlas"],"010-0100","Mira",
[("Mira","010-0100"),("Jin","010-0200")],["Harbor Signals","Soundings"]],
[harbor.publisher.city,list(north.book_set.order_by("pk").values_list("title",flat=True)),
mira.profile.phone,Profile.objects.get(pk=mira.profile_id).author.name,[(a.name,a.profile.phone) for a in harbor.authors.order_by("pk")],
list(jin.book_set.order_by("pk").values_list("title",flat=True))])
def amounts(query):
return [(title,str(price)) for title,price in query]
direct=amounts(Book.objects.filter(publisher__name="North Press").order_by("pk").values_list("title","price"))
backward=amounts(Publisher.objects.filter(name="North Press").order_by("book__pk").values_list("book__title","book__price"))
queries=check("Traverse relationships with double-underscore lookups",
"Compare paired forward and reverse projections on all three kinds of relationship",
["North Press","Jin","Mira"],
[[("Harbor Signals","20.00"),("Coastal Atlas","30.00")]]*2+
[["Harbor Signals","Soundings"],["Harbor Signals","Soundings"],"010-0100","010-0100"],
[direct,backward,list(Book.objects.filter(authors__name="Jin").order_by("pk").values_list("title",flat=True)),
list(Author.objects.filter(name="Jin").order_by("book__pk").values_list("book__title",flat=True)),
Author.objects.values_list("profile__phone",flat=True).get(name="Mira"),
Profile.objects.values_list("phone",flat=True).get(author__name="Mira")])
return [schema,foreign,m2m,object_case,queries]
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/relationship_exercise.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
relationship_exercise.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14、Django 5.2.19、SQLite、Edge。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202612a177.zip
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a164.zip