contains_eager
和joinedload
在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']
有人可以显示更多特定的代码示例吗?
最佳答案
不要忘记很多一对一。区别在于,使用contains_eager()
可以指示SQLA有关现有联接或应用于填充关系的联接。这样,您也可以populate using a filtered subset。
另一方面,joinedload()
竭尽全力使填充所需的连接完全透明,并且它们不应影响原始查询的结果,如The Zen of Joined Eager Loading中所述。换句话说,您不能使用联接关系进行过滤等。