SQLAlchemy contains_eager和joinedload之间的区别

时间:2018-05-05 09:29:36

标签: python sql sqlalchemy

contains_eagerjoinedload之间SQLAlchemy的区别是什么。 我阅读了关于contains_eager的manual,以及关于joinedload的manual。它们都可用于加载一对多相关行或多对一行。

他们正在生成相同的sql:

query = session.query(User).\
    outerjoin(adalias, User.addresses).\
    options(contains_eager(User.addresses, alias=adalias)).all()

...

SELECT
    users.user_id AS users_user_id,
    users.user_name AS users_user_name,
    adalias.address_id AS adalias_address_id,
    adalias.user_id AS adalias_user_id,
    adalias.email_address AS adalias_email_address,
    (...other columns...)
FROM users
LEFT OUTER JOIN email_addresses AS email_addresses_1
ON users.user_id = email_addresses_1.user_id


>>> jack = session.query(User).\
... options(joinedload(User.addresses)).\
... filter_by(name='jack').all()

SELECT
    addresses_1.id AS addresses_1_id,
    addresses_1.email_address AS addresses_1_email_address,
    addresses_1.user_id AS addresses_1_user_id,
    users.id AS users_id, users.name AS users_name,
    users.fullname AS users_fullname,
    users.password AS users_password
FROM users
LEFT OUTER JOIN addresses AS addresses_1
    ON users.id = addresses_1.user_id
WHERE users.name = ?
['jack']

有人可以展示更具体的代码示例吗?

1 个答案:

答案 0 :(得分:1)

不要忘记多对多和一对一。不同之处在于,使用contains_eager()指示SQLA关于应该用于填充关系的现有连接或连接。这样你也可以populate using a filtered subset

另一方面,

joinedload()竭尽全力使填充所需的连接完全透明,它们不应影响原始查询的结果,如The Zen of Joined Eager Loading中所述。换句话说,您不能使用连接关系进行过滤等。