简体   繁体   English

SQLAlchemy 中的 Eager Inner Join

[英]Eager Inner Join in SQLAlchemy

I must be a moron, because I cannot figure out how to ask SQLAlchemy to perform a simple, non-lazy inner join.我一定是个白痴,因为我不知道如何让 SQLAlchemy 执行一个简单的、非惰性的内部联接。 In other words, return all the results in a single query .换句话说,在单个查询中返回所有结果。

The raw SQL query I would like to run is:我想运行的原始 SQL 查询是:

select
  city.population,
  state.name
from 
  city c inner join state s
    on c.state_id = s.id

The SQLAlchemy statement I'm using is:我正在使用的 SQLAlchemy 语句是:

session.query(City.population, State.name).all()

The City and State models already have the relationship defined, and the SQLAlchemy statement returns the correct values. City 和 State 模型已经定义了关系,并且 SQLAlchemy 语句返回正确的值。 But it takes forever, because it is doing individual "lazy" loads for the second value of every row in the recordset.但它需要永远,因为它正在为记录集中每一行的第二个值执行单独的“延迟”加载。 The FROM statement is simply: FROM city, state FROM 语句很简单: FROM city, state

  • I have tried various configurations of options(joinedload(something here))我已经尝试了各种配置的options(joinedload(something here))
  • I have read "The Zen of Eager Loading," I find it unhelpful because it assumes the query is asking for entire model objects, not specific columns.我读过“热切加载的禅”,我发现它没有帮助,因为它假设查询要求整个模型对象,而不是特定的列。
  • I read this answer which says joinedload is "meant to be entirely transparent" which, I can't agree with, because it seems to require a re-arrangement of the core query.我读了这个答案,其中说joinedload“意味着完全透明”,我不能同意这一点,因为它似乎需要重新安排核心查询。

I might be slightly off here, but have you tried explicitly passing the join condition?我可能在这里有点偏离,但是您是否尝试过明确地传递连接条件?

q = session.query(City.population, State.name).join(State).all()

Also, assuming your objective is the initial query, have you tried a few tweaks in the sqlalchemy syntax to actually get the same statement?另外,假设您的目标是初始查询,您是否尝试过对sqlalchemy语法进行一些调整以实际获得相同的语句?

print (q.statement)

Lastly, Query classes have a method enable_eagerloads() .最后, Query类有一个方法enable_eagerloads() From the docs :文档

Control whether or not eager joins and subqueries are rendered.控制是否呈现急切连接和子查询。

When set to False, the returned Query will not render eager joins regardless of joinedload(), subqueryload() options or mapper-level lazy='joined'/lazy='subquery' configurations.当设置为 False 时,无论 joinload()、subqueryload() 选项或映射器级别的 lazy='joined'/lazy='subquery' 配置如何,返回的 Query 都不会呈现预先连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM