
本文旨在帮助开发者理解 SQLAlchemy 中关系(relationship)的使用。当使用 SQLAlchemy 定义了父类和子类之间的关系后,直接访问父类的子类列表可能会得到空列表。这是因为 SQLAlchemy 默认情况下不会立即加载关系,需要在 flush() 或 commit() 操作后才会更新关系。本文将通过示例代码,演示如何通过 flush() 方法或者在创建父类对象时手动关联子类对象来正确地获取父类关联的子类对象。
理解 SQLAlchemy 关系(Relationship)
SQLAlchemy 的关系(relationship)功能用于定义表之间的关联。在 ORM 层面,它允许我们像访问对象的属性一样访问关联表的数据。例如,一个 Parent 类可以有一个 children 关系,指向多个 Child 类对象。
在定义关系时,需要指定 back_populates 参数,以便 SQLAlchemy 知道关系的另一端是什么。例如,在 Parent 类中,children = relationship('Child', back_populates='parent') 表示 Parent 类有一个名为 children 的关系,它与 Child 类的 parent 关系相关联。
示例代码分析
以下代码展示了如何定义 Parent 和 Child 类,并使用 SQLAlchemy 创建表和插入数据:
import sys
from sqlalchemy import (
create_engine,
Integer,
String,
BigInteger,
)
from sqlalchemy.schema import (
Column,
ForeignKey,
)
from sqlalchemy.sql import select
from sqlalchemy.orm import declarative_base, Session, aliased, relationship, joinedload
Base = declarative_base()
# 替换为你的数据库用户名、密码和数据库名
username, password, db = "your_username", "your_password", "your_database"
engine = create_engine(f"postgresql+psycopg2://{username}:{password}@/{db}", echo=False)
class Parent(Base):
__tablename__ = "parents"
id = Column(Integer, primary_key=True)
name = Column(String)
children = relationship('Child', back_populates='parent')
class Child(Base):
__tablename__ = "childs"
id = Column(Integer, primary_key=True)
name = Column(String)
parent_id = Column(Integer, ForeignKey('parents.id'))
parent = relationship('Parent', back_populates='children')
Base.metadata.create_all(engine)注意: 将 your_username, your_password, your_database 替换成你自己的数据库信息。
获取关联对象的方法
方法一:使用 flush() 方法
flush() 方法将当前会话中的所有更改同步到数据库,包括插入、更新和删除操作。在 flush() 方法执行后,SQLAlchemy 会更新对象之间的关系。
def test1():
""""""
with Session(engine) as session:
mother = Parent(id=1, name='Sarah')
c1 = Child(id=22, parent_id=mother.id, name='Alice')
c2 = Child(id=23, parent_id=mother.id, name='Bob')
# Children and parent(s) are not set.
assert not mother.children and not c1.parent and not c2.parent
session.add(mother)
session.add(c1)
session.add(c2)
# Nothing changed.
assert not mother.children and not c1.parent and not c2.parent
session.flush()
# Now children and parent(s) are set.
assert mother.children and c1.parent and c2.parent
test1()在这个例子中,我们首先创建了 Parent 和 Child 对象,并将它们添加到会话中。在调用 flush() 方法之前,mother.children 仍然是空的。但是在调用 flush() 方法之后,mother.children 会被更新为包含 c1 和 c2 对象。
方法二:手动关联对象
另一种方法是在创建 Parent 对象时,手动将 Child 对象添加到 children 列表中。
def test2():
""""""
with Session(engine) as session:
c1 = Child(id=22, name='Alice')
c2 = Child(id=23, name='Bob')
mother = Parent(id=1, name='Sarah', children=[c1, c2])
# Children and parents are now set but their parent_ids are not set.
assert mother.children and c1.parent and c2.parent and not c1.parent_id and not c2.parent_id
session.add(mother)
session.add(c1)
session.add(c2)
# Nothing changed.
assert mother.children and c1.parent and c2.parent and not c1.parent_id and not c2.parent_id
session.flush()
# Now children are set and parent ids are set.
assert mother.children and c1.parent and c2.parent and c1.parent_id and c2.parent_id
test2()在这个例子中,我们在创建 mother 对象时,将 c1 和 c2 对象添加到 children 列表中。这样,在创建 mother 对象之后,mother.children 就会包含 c1 和 c2 对象。但是,需要注意的是,此时 c1 和 c2 对象的 parent_id 仍然没有设置,需要在调用 flush() 方法之后才会设置。
注意事项
- 在 SQLAlchemy 中,关系的加载方式有多种,包括 lazy、eager 和 joined。默认情况下,关系是 lazy 加载的,这意味着只有在访问关系时才会加载数据。如果需要立即加载关系,可以使用 joinedload 或 eagerload 方法。
- flush() 方法只是将更改同步到数据库,但不会提交事务。如果需要提交事务,需要调用 commit() 方法。
- 在处理大量数据时,频繁调用 flush() 方法可能会影响性能。可以考虑批量插入数据,并在最后一次性调用 flush() 方法。
总结
通过本文的介绍,相信你已经了解了如何在 SQLAlchemy 中获取父类关联的子类对象。flush() 方法在 SQLAlchemy 中起着非常重要的作用,它可以同步会话中的更改,并更新对象之间的关系。在实际开发中,可以根据具体情况选择合适的方法来获取关联对象。










