用 Django ORM 操作书目、出版组和作者关系
验证外键、一对一与多对多的结构、保存、正反向访问和跨表查询。
学完这一章,你能够
- 验证外键、一对一与多对多的结构、保存、正反向访问和跨表查询。
为三种关系找到存储位置
书目与出版组是多对一。外键在多的一边,也就是 Book.publisher。作者与详情是一对一,Author.profile 使用 OneToOneField,在数据库中落实为外键和唯一约束。书目与作者是多对多,由 Django 创建中间关系表。
Book 还含书名、DecimalField 价格与日期,Publisher 含名称、城市、EmailField。EmailField 基于 CharField,负责邮箱格式校验,存储类型由后端决定。Author 有年龄,Profile 有三种可见性选项、示例电话、地址和生日。
当前 Django 需要为外键和一对一明确 on_delete。CASCADE 是 Django 的删除收集行为,本章为选定关系声明它。更新主键或外键关联需要另行设计,不能把删除策略当作级联更新。
先保存关联目标,再创建引用
先迁移创建各表。填充书目之前创建出版组,填充作者之前创建详情。本站用 ORM 建立默认样例,也在临时事务执行参数化 SQL,核对插入和反向访问后回滚。
对象写法是 Book.objects.create(publisher=north, ...);已知主键时可写 publisher_id=north.pk。两种写法都返回已保存的 Book。外键列名默认在属性名后加 _id。给书目传未保存的出版组对象会被拒绝。
分清外键反向管理器的能力
书目通过 book.publisher 访问单个出版组。出版组通过 publisher.book_set 访问一组书目。给反向外键管理器调用 add 时要传模型对象,不能只传整数主键。本站用它转移一条已保存书目并回滚。
只有允许 NULL 的反向外键关系才提供 remove 与 clear。本章另设可空 Draft.publisher,实测两种方法都让外键变回 None。必填 Book.publisher 不提供这两个方法。
为多对多中间表添加和移除关联
书目 authors 与作者 book_set 两侧都有管理器。多对多 add 可以传模型对象或主键,也能用 * 展开 QuerySet 或主键列表。保存书目后才能写中间表,重复 add 不会产生重复关系。
反向 add 可把已保存书目连给作者。反向 create 会新建书目并建立关联,同时返回新对象。remove 与 clear 删除中间关系,保留书目和作者本身。本站用回滚检查这些动作的返回值和实际记录。
从实例出发跨表访问
正向外键 book.publisher.city 得出版城市,反向 publisher.book_set.all() 可遍历该组书目。
正向一对一 author.profile.phone 得详情中的分机,反向 profile.author.name 得作者名。默认反向一对一访问器是小写模型名,无 _set。
从 book.authors.all() 遍历作者,可以继续读各自 profile.phone。反向从 author.book_set.all() 查看该作者的书目。样例既有两个作者的书,也有暂无作者的书。
从 QuerySet 直接跨关系筛选和取值
正向外键查找用 publisher__name,反向查询名默认是小写模型名 book,例如 book__title 和 book__price。实例管理器名 book_set 与查询名 book 是两个接口。
多对多正向用 authors__name 找到 Jin 的书,反向从 Author 用 book__title 取同样的书目。一对一正向用 profile__phone,反向用 author__name。
浏览器实际从迁移后的数据库查询关联记录。本站截图显示出版城市和作者示例分机,包含空关联的输出。
逐项运行 Django 关系操作
展开查看收起
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))
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
完整开发工程
解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
比较对象访问与双下划线投影,注意外键可空条件以及 join 表与实体行的区别。