简体   繁体   中英

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. In other words, return all the results in a single query .

The raw SQL query I would like to run is:

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:

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. 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

  • I have tried various configurations of 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.

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?

print (q.statement)

Lastly, Query classes have a method 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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