一对多关系 - 原始映射
一对多在数据库中就是使用外键,看一下如何定义Model
先创建一个制造商的数据表:
class Product(Model):
__tablename__ = 'products'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(64), index=True, unique=True)
manufacturer: Mapped[str] = mapped_column(String(64), index=True)
year: Mapped[int] = mapped_column(index=True)
country: Mapped[Optional[str]] = mapped_column(String(32))
cpu: Mapped[Optional[str]] = mapped_column(String(32))
def __repr__(self):
return f'Product({self.id}, "{self.name}")'
class Manufacturer(Model):
__tablename__ = 'manufacturers'
id:Mapped[int] = mapped_column(primary_key=True)
name:Mapped[str] = mapped_column(String(64), index=True, unique=True)
def __repr__(self):
return f'Manufacturer({self.id}, "{self.name}")'
之后的关键是要把Product类中的manufacture字段替换成外键:
from typing import Optional
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column
from db import Model
from sqlalchemy import ForeignKey
class Product(Model):
__tablename__ = 'products'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(64), index=True, unique=True)
manufacturer_id: Mapped[str] = mapped_column(ForeignKey('manufacturers.id'), index=True)
year: Mapped[int] = mapped_column(index=True)
country: Mapped[Optional[str]] = mapped_column(String(32))
cpu: Mapped[Optional[str]] = mapped_column(String(32))
def __repr__(self):
return f'Product({self.id}, "{self.name}")'
class Manufacturer(Model):
__tablename__ = 'manufacturers'
id:Mapped[int] = mapped_column(primary_key=True)
name:Mapped[str] = mapped_column(String(64), index=True, unique=True)
def __repr__(self):
return f'Manufacturer({self.id}, "{self.name}")'
这里注意关联的表名实际使用的是Manufacturer.__tablename__ .id,这个和JPA的映射很像,都是映射到字符串的名称,而不是类名。
而且由于类型不带有Optional,所以实际上添加了NOT NULL约束。
采用上边外键映射的方式,查询起来并不方便,所以要加上采用SA提供的关系映射(个人感觉这里非常像JPA的映射了,只不过JPA通过注解,这里实际上要重新写一个新的属性):
from typing import Optional
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from db import Model
from sqlalchemy import ForeignKey
class Product(Model):
__tablename__ = 'products'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(64), index=True, unique=True)
manufacturer_id: Mapped[str] = mapped_column(ForeignKey('manufacturers.id'), index=True)
year: Mapped[int] = mapped_column(index=True)
country: Mapped[Optional[str]] = mapped_column(String(32))
cpu: Mapped[Optional[str]] = mapped_column(String(32))
manufacturer: Mapped['Manufacturer'] = relationship(
back_populates='products'
)
def __repr__(self):
return f'Product({self.id}, "{self.name}")'
class Manufacturer(Model):
__tablename__ = 'manufacturers'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(64), index=True, unique=True)
def __repr__(self):
return f'Manufacturer({self.id}, "{self.name}")'
products: Mapped[list['Product']] = relationship(
back_populates='manufacturer'
)
现在Product和Manufacturer两个类,各自拥有一个高级属性,这个属性并不直接对应数据库的列,而是描述了关系映射。
从Manufacturer 角度来看,一个制造商拥有多个产品,所以映射的类型是list['Product'],注意这里是字符串形式的类名。而一个产品只有一个对应的Manufacturer ,所以类型就是Mapped['Manufacturer'] 。
back_populates设置的是另外一端对应的属性名称:
manufacturer: Mapped['Manufacturer'] = relationship(
back_populates='products'
)
# 这里的products指的是另外一端对应到Manufacturer类里的叫做products的属性。而这个属性正好已经设置了对应到自己的映射。设计的高级属性具有append()和remove()方法,用来向映射集合中添加或者删除元素,会被转换成实际的外键更改。
这里并没有单独保存每一个P再设置关系,因为级联添加了元素。
一对多查询
一对多的查询就可以使用刚才创建的高级属性,而不必再使用原始的列。
with Session() as session:
with session.begin():
with open('products.csv') as f:
product = session.get(Product,10)
print(product.manufacturer)
print(product.manufacturer.products)这个如果使用过Django ORM的会非常熟悉,直接就可以获取对应的对象。
如果需要同时查询来自多个表的列,只需要在select后边加上.join(),select中的第一个对象是起始表,join要join另外一张表,另外一张表用起始表的关联字段表示即可。
with Session() as session:
with session.begin():
with open('products.csv') as f:
query = select(
Product.name,Manufacturer.name
).join(Product.manufacturer)
result = session.execute(query).all()
print(result)左右连接
在此查询中,select语句指定来自不同表的两个属性。每当查询涉及多个表时,SA需要知道如何连接这些表,这也是加入join子句的原因。在使用 ORM 模块时,join的参数可以是两个关系属性之一,SA会从中推算出所有内容。由于这两个关系对象通过 back_populates 选项相连,通常 join 子句中给出哪一个并不重要。在上述示例查询中,将 Product.manufacturer 传递给 join意味着 Product 会位于连接的左侧,而 Manufacturer 会在右侧。如果传递的是 Manufacturer.products,则会反转,注意左右连接在SQL中是有不同方式的。
懒加载与饥渴加载
懒加载的问题
默认的情况下,是懒加载,需要用的时候才读取,在命令行不关闭session的时候可以看到,每一次访问不在缓存中的数据,都会触发一次查询。这是SA默认使用了select加载器,这是一个懒加载器。如果使用连接加载器,就可以一次性获取数据。
实验一下,将engine设置为显示SQL语句,然后在IDE 的 python console (当前环境)中输入:
from models import Product, Manufacturer
from sqlalchemy import select
session = Session()
m = session.scalar(
select(Manufacturer)
.where(Manufacturer.name == 'Texas Instruments'))
# 这里会触发实际的数据库查询
2026-11-26 15:12:27,897 INFO sqlalchemy.engine.Engine select pg_catalog.version()
2026-11-26 15:12:27,898 INFO sqlalchemy.engine.Engine [raw sql] {}
2026-11-26 15:12:27,899 INFO sqlalchemy.engine.Engine select current_schema()
2026-11-26 15:12:27,899 INFO sqlalchemy.engine.Engine [raw sql] {}
2026-11-26 15:12:27,899 INFO sqlalchemy.engine.Engine show standard_conforming_strings
2026-11-26 15:12:27,900 INFO sqlalchemy.engine.Engine [raw sql] {}
2026-11-26 15:12:27,902 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2026-11-26 15:12:27,907 INFO sqlalchemy.engine.Engine SELECT manufacturers.id, manufacturers.name
FROM manufacturers
WHERE manufacturers.name = %(name_1)s::VARCHAR
2026-11-26 15:12:27,907 INFO sqlalchemy.engine.Engine [generated in 0.00021s] {'name_1': 'Texas Instruments'}
# m是查出来的对象,查一下m自己的属性
m.name
m
# 输入上边的部分并不会触发新的查询
# 输入m.products会立刻触发查询
m.products
2026-11-26 15:16:45,227 INFO sqlalchemy.engine.Engine SELECT products.id, products.name, products.manufacturer_id, products.year, products.country, products.cpu
FROM products
WHERE %(param_1)s::INTEGER = products.manufacturer_id
2026-11-26 15:16:45,228 INFO sqlalchemy.engine.Engine [generated in 0.00041s] {'param_1': 66}
[Product(132, "TI-99/4"), Product(133, "TI-99/4A")]
# 从另外一方查询也是这样,这是因为当前使用的是select选择器,这是一个lazy选择器,并不会加载对应的关系数据,遇到才能加载懒惰加载器的最大问题是,如果在session中查询了某个对象,在session之外去查询对应的关联数据,就会出现错误,因为会话已经关闭,看这个例子:
from sqlalchemy import select
from db import Model, Session, engine
from models import Product, Manufacturer
with Session() as session:
with session.begin():
with open('products.csv') as f:
m = session.scalar(
select(Manufacturer)
.where(Manufacturer.name == 'Texas Instruments'))
print(m.name)
# 代码执行到查询products的时候报错,当前不在一个session内,所以无法获取数据
# sqlalchemy.orm.exc.DetachedInstanceError: Instance <Manufacturer at 0x1a9d5bbbb60> is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: https://sqlalche.me/e/21/bhk3)
print(m.products)
# 下边的语句会触发N+1条查询,所以不能如此操作,要一次性加载出来
with Session() as session:
with session.begin():
with open('products.csv') as f:
q = select(Product)
for p in session.scalars(q):
print(p.name, p.manufacturer.name)在实际的业务当中,应该使用尽可能少的数据,一次性将所有数据查询出来,而不是在整个视图中反复进行查询。
有三种办法:
解决方案1 - 直接查询所需的数据
直接查询出全部要的数据,如果对于SQL非常熟悉,则可以细致的查询出所有需要的字段和结果,一次性返回所有需要的数据。
with Session() as session:
with session.begin():
with open('products.csv') as f:
q = select(Product, Manufacturer).join(Product.manufacturer)
for p in session.scalars(q):
print(p.name, p.manufacturer.name)
# 对应的语句就是一个大连表全部查询出来:
# SELECT products.id, products.name, products.manufacturer_id, products.year, products.country, products.cpu, manufacturers.id AS id_1, manufacturers.name AS name_1 FROM products JOIN manufacturers ON manufacturers.id = products.manufacturer_id解决方案2 - 每次使用饥渴加载的连接器
每次查询的时候使用饥渴加载的连接器(SA叫关系加载器),会在查询Product的时候,就把对应的关联数据一并查询出来。
注意这个使用的是左连接,要比解决方案1中生成的普通JOIN更好。
from sqlalchemy.orm import joinedload
# 这段代码生成的是一个左连接语句,比刚才使用的.join()更加明确,.join()生成的是普通JOIN。
# SELECT products.id, products.name, products.manufacturer_id, products.year, products.country, products.cpu, manufacturers_1.id AS id_1, manufacturers_1.name AS name_1 FROM products LEFT OUTER JOIN manufacturers AS manufacturers_1 ON manufacturers_1.id = products.manufacturer_id
with Session() as session:
with session.begin():
with open('products.csv') as f:
q = select(Product).options(joinedload(Product.manufacturer))
for p in session.scalars(q):
print(p.name, p.manufacturer.name)解决方案3 - 在类的多对一关系字段上指定加载器
第三种办法,在类的关系字段上通过指定lazy属性的值来指定加载器:
class Product(Model):
__tablename__ = 'products'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(64), index=True, unique=True)
manufacturer_id: Mapped[str] = mapped_column(ForeignKey('manufacturers.id'), index=True)
year: Mapped[int] = mapped_column(index=True)
country: Mapped[Optional[str]] = mapped_column(String(32))
cpu: Mapped[Optional[str]] = mapped_column(String(32))
manufacturer: Mapped['Manufacturer'] = relationship(
lazy='joined',
back_populates='products'
)
def __repr__(self):
return f'Product({self.id}, "{self.name}")'lazy可以有多个指定,在类的文档里有如下内容,其默认值就是select即懒加载。
:param lazy='select': specifies
How the related items should be loaded. Default value is
``select``. Values include:
* ``select`` - items should be loaded lazily when the property is
first accessed, using a separate SELECT statement, or identity map
fetch for simple many-to-one references.
懒加载,使用单独一条语句进行加载
* ``immediate`` - items should be loaded as the parents are loaded,
using a separate SELECT statement, or identity map fetch for
simple many-to-one references.
加载父实体的时候立刻加载,使用单独一条语句
* ``joined`` - items should be loaded "eagerly" in the same query as
that of the parent, using a JOIN or LEFT OUTER JOIN. Whether
the join is "outer" or not is determined by the
:paramref:`_orm.relationship.innerjoin` parameter.
使用JOIN或者左连接加载
* ``subquery`` - items should be loaded "eagerly" as the parents are
loaded, using one additional SQL statement, which issues a JOIN to
a subquery of the original statement, for each collection
requested.
使用子查询的方式连接
* ``selectin`` - items should be loaded "eagerly" as the parents
are loaded, using one or more additional SQL statements, which
issues a JOIN to the immediate parent object, specifying primary
key identifiers using an IN clause.
使用额外的IN语句查询
* ``raise`` - lazy loading is disallowed; accessing
the attribute, if its value were not already loaded via eager
loading, will raise an :exc:`~sqlalchemy.exc.InvalidRequestError`.
This strategy can be used when objects are to be detached from
their attached :class:`.Session` after they are loaded.
* ``raise_on_sql`` - lazy loading that emits SQL is disallowed;
accessing the attribute, if its value were not already loaded via
eager loading, will raise an
:exc:`~sqlalchemy.exc.InvalidRequestError`, **if the lazy load
needs to emit SQL**. If the lazy load can pull the related value
from the identity map or determine that it should be None, the
value is loaded. This strategy can be used when objects will
remain associated with the attached :class:`.Session`, however
additional SELECT statements should be blocked.
两个raise都是如果触发了隐式加载,会报异常,适合跟踪意外触发了隐式加载的程序代码
* ``write_only`` - the attribute will be configured with a special
"virtual collection" that may receive
:meth:`_orm.WriteOnlyCollection.add` and
:meth:`_orm.WriteOnlyCollection.remove` commands to add or remove
individual objects, but will not under any circumstances load or
iterate the full set of objects from the database directly. Instead,
methods such as :meth:`_orm.WriteOnlyCollection.select`,
:meth:`_orm.WriteOnlyCollection.insert`,
:meth:`_orm.WriteOnlyCollection.update` and
:meth:`_orm.WriteOnlyCollection.delete` are provided which generate SQL
constructs that may be used to load and modify rows in bulk. Used for
large collections that are never appropriate to load at once into
memory.
禁用关系加载
The ``write_only`` loader style is configured automatically when
the :class:`_orm.WriteOnlyMapped` annotation is provided on the
left hand side within a Declarative mapping. See the section
:ref:`write_only_relationship` for examples.
.. versionadded:: 2.0
.. seealso::
:ref:`write_only_relationship` - in the :ref:`queryguide_toplevel`
* ``dynamic`` - the attribute will return a pre-configured
:class:`_query.Query` object for all read
operations, onto which further filtering operations can be
applied before iterating the results.
The ``dynamic`` loader style is configured automatically when
the :class:`_orm.DynamicMapped` annotation is provided on the
left hand side within a Declarative mapping. See the section
:ref:`dynamic_relationship` for examples.
.. legacy:: The "dynamic" lazy loader strategy is the legacy form of
what is now the "write_only" strategy described in the section
:ref:`write_only_relationship`.
.. seealso::
:ref:`dynamic_relationship` - in the :ref:`queryguide_toplevel`
:ref:`write_only_relationship` - more generally useful approach
for large collections that should not fully load into memory
* ``noload`` - no loading should occur at any time. The related
collection will remain empty.
.. deprecated:: 2.1 The ``noload`` loader strategy is deprecated and
will be removed in a future release. This option produces incorrect
results by returning ``None`` for related items.
* True - a synonym for 'select'
* False - a synonym for 'joined'
* None - a synonym for 'noload'
.. seealso::
:ref:`orm_queryguide_relationship_loaders` - Full documentation on
relationship loader configuration in the :ref:`queryguide_toplevel`.注意设置True就是懒加载,设置False就是JOIN加载,设置None是不加载,可见SA已经给了一些默认推荐的选项。
一对多的加载 - 使用selectin或者unique()
注意刚才字段是在多对一上使用joined ,这个是可以的,因为正常就需要连表查出来。
但不能简单的将lazy='joined'复制到例子中的Manufacturer类的products字段上,因为一次性全部查出来的话,左边会有重复的Manufacturer,所以必须要去重,或者使用selectin才可以。
from sqlalchemy import select
from db import Model, Session, engine
from models import Product, Manufacturer
class Manufacturer(Model):
__tablename__ = 'manufacturers'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(64), index=True, unique=True)
def __repr__(self):
return f'Manufacturer({self.id}, "{self.name}")'
products: Mapped[list['Product']] = relationship(
lazy='selectin',
back_populates='manufacturer'
)
with Session() as session:
with session.begin():
with open('products.csv') as f:
q = select(Manufacturer)
result = session.scalars(q).all()
for each in result:
print(each)
print(len(result))
# 如果不使用selectin,也可以使用session.scalars(q).unique()
# 因为多对一的一方,这条语句生成的SQL语句原始结果依然是149行,但是去重之后,最后的正确结果是76行数据,要执行一个去重的动作,如果join之后就是149行,结果集是不正确的,这个不正确不是说SQL语句查询的149行不正确,而是149行经过封装之后的数量不正确,应该是76行。级联选项
默认的级联选项在relationship中使用cascade='save-update, merge' ,这个选项在新增父对象的时候,会自动新增已经设置了关系的子对象。注意要先删除干净所有的子对象,才能够删除父对象,也这是常见的约束。
还有一种配置是'all, delete-orphan' ,all除了孤儿之外都不涵盖,再加上孤儿就是全部操作都级联。
一般来说,在一对多的一方,可以配置'all, delete-orphan' ,在删除一的时候,对应的多方就被全部删除。
现有的例子里,如果一个Manufacturer还有对应的Product ,无法直接删除,设置新的配置:
class Manufacturer(Model):
__tablename__ = 'manufacturers'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(64), index=True, unique=True)
def __repr__(self):
return f'Manufacturer({self.id}, "{self.name}")'
products: Mapped[list['Product']] = relationship(
cascade='all, delete-orphan',
back_populates='manufacturer'
)
增加了cascade='all, delete-orphan' 之后,就可以直接删除Manufacture对象了,相关的Product会被一起删除。
解除对应关系
解除对应关系,在一对多的一方,其设置的多的属性上自带remove和append方法,用于向对应关系删除或者添加数据。
注意刚才已经设置了删除孤儿,所以会直接删除孤儿对象。如果没有设置,SA会将外键设置为NULL,但因为规定了外键不为NULL,所以会报错。
如果需要严格的对应关系,则设置成all+孤儿 是一个比较好的选择。
从一方来删除:
from db import Model, Session, engine
from models import Product, Manufacturer
with Session() as session:
with session.begin():
with open('products.csv') as f:
m = session.get(Manufacturer, 5)
print((m.products))
p = session.get(Product, 18)
print(p)
m.products.remove(p)
session.flush()
print((m.products))刷新后再次查询,id=18 的Product对象已经不存在。
从多方删除,只需要将manufacturer属性设置为None即可,但由于使用了NOT NULL约束,所以会得到错误。这个时候只需要直接删除一方即可。