How to make a subquery in sqlalchemy


FROM Residents
WHERE apartment_id IN (SELECT ID
                       FROM Apartments
                       WHERE postcode = 2000)

I’m using sqlalchemy and am trying to execute the above query. I haven’t been able to execute it as raw SQL using db.engine.execute(sql) since it complains that my relations doesn’t exist… But I succesfully query my database using this format: session.Query(Residents).filter_by(???).
I cant not figure out how to build my wanted query with this format, though.

Asked By: user2651804



You can create subquery with subquery method

subquery = session.query(
query = session.query(Residents).filter(Residents.apartment_id.in_(subquery))
Answered By: r-m-n

I just wanted to add, that if you are using this method to update your DB, make sure you add the synchronize_session='fetch' kwarg. So it will look something like:

subquery = session.query(
query = session.query(Residents).
          update({"key": value}, synchronize_session='fetch')

Otherwise you will run into issues.

Answered By: Kevin Postlethwait
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.