关系与连接
为相关表建立模型
关系与连接 是 CoddyKit 上的免费 Python Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python Academy 课程共包含 4 节课。
关联表
真实数据之间相互关联:作者可以有多本书,订单可以包含多个项目。SQLAlchemy 使用关系和外键来表示这些关联。
# Author 1 --- many --- Book
# A foreign key on Book points back to Author
print('One-to-many is the most common link')外键
外键列存储关联行的主键。请使用 ForeignKey('table.column') 声明它。
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column
# author_id: Mapped[int] = mapped_column(ForeignKey('authors.id'))
print('ForeignKey links child to parent')定义父模型
父模型使用 relationship() 保存子对象集合。
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
from typing import List
class Base(DeclarativeBase):
pass
class Author(Base):
__tablename__ = 'authors'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
books: Mapped[List['Book']] = relationship(back_populates='author')
print('Author.books holds related Book objects')定义子模型
子模型包含外键列,以及一个指回父模型的 relationship()。
from sqlalchemy import ForeignKey
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
class Base(DeclarativeBase):
pass
class Book(Base):
__tablename__ = 'books'
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str]
author_id: Mapped[int] = mapped_column(ForeignKey('authors.id'))
author: Mapped['Author'] = relationship(back_populates='books')
print('Book.author points to its parent')双向关联
back_populates 会将两个关系关联起来,因此更新一侧时,另一侧也会自动反映相应变化。
# author.books.append(book) also sets book.author = author
# Both sides stay in sync automatically
print('back_populates keeps both sides consistent')使用关系
建立关联后,您可以像访问普通属性一样遍历关系:author.books 是一个列表,而 book.author 是父对象。
# for book in author.books:
# print(book.title)
# print(book.author.name)
print('Navigate with plain attribute access')构建对象图
将子对象追加到父对象的集合中。将父对象添加到会话后,更改会级联到子对象。
# a = Author(name='Rowling')
# a.books.append(Book(title='Book 1'))
# session.add(a)
# session.commit() # author and book both saved
print('Cascade saves the whole object graph')隐式连接
访问 book.author 会触发 SQLAlchemy 自动加载关联行,这个过程会在后台进行(延迟加载)。
# Accessing book.author runs a SELECT if not loaded yet
# This is lazy loading
print('Lazy loading fetches related rows on access')显式连接
如果要跨表过滤,请在 select 中使用 join()。这会生成 SQL JOIN。
from sqlalchemy import select
# stmt = select(Book).join(Author).where(Author.name == 'Rowling')
# books = session.scalars(stmt).all()
print('join(Author) filters across the relationship')预加载
为了避免执行许多小查询,请使用 joinedload 或 selectinload 预先加载关联行。
from sqlalchemy import select
from sqlalchemy.orm import selectinload
# stmt = select(Author).options(selectinload(Author.books))
print('selectinload preloads children in one extra query')多对多关系
对于多对多关联,关联表会连接两侧。relationship() 使用 secondary= 指向该表。
# students <-> courses via a 'enrollments' association table
# courses: Mapped[List['Course']] = relationship(secondary=enrollments)
print('secondary= models many-to-many')快速检查
测试您对关系的理解。
回顾
您学会了对关联表进行建模。
ForeignKey在子对象的列中存储关联- 带有
back_populates的relationship()会连接两侧 - 可以像访问普通属性一样遍历关联;延迟加载会在访问时获取数据
join()用于跨表过滤;selectinload用于预加载;secondary=用于处理多对多关系
常见问题解答
「关系与连接」课时是免费的吗?
是的 — 「关系与连接」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python Academy 课程的其余内容,请升级到 CoddyKit PRO。 Python Academy 课程共包含 4 节课。
「关系与连接」这节课中我会学到什么?
为相关表建立模型 你通过在浏览器中直接运行的动手代码来练习 Python Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Python Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Python Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「关系与连接」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Python Academy 课中编写并运行代码吗?
能。每节 Python Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。