pythonormsqlalchemypython-db-api

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


Solution

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