58
SELECT *
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.

2 Answers 2

123

You can create subquery with subquery method

subquery = session.query(Apartments.id).filter(Apartments.postcode==2000).subquery()
query = session.query(Residents).filter(Residents.apartment_id.in_(subquery))
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you my lord. Finally an answer that does not involve messing around with the orm.
the query is type of <class 'flask_sqlalchemy.BaseQuery'> upon which I am not able to call .all() to get the results. Can you explain how do I use the query object ?
It's not clear to me how I would bind subquery "parameters" to the main query by using this method (as the subquery is defined before the query itself).
In SQLAlchemy 1.4 this use case gives me a warning: SAWarning: Coercing Subquery object into a select() for use in IN(); please pass a select() construct explicitly. Is there an example formatting for this issue? I haven't found one in the docs yet.
Answered my own simple question. Just write it as follows to resolve the warning: from sqlalchemy.sql import select and query = session.query(Residents).filter(Residents.apartment_id.in_(select(subquery)))
|
3

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(Apartments.id).filter(Apartments.postcode==2000).subquery()
query = session.query(Residents).\
          filter(Residents.apartment_id.in_(subquery)).\
          update({"key": value}, synchronize_session='fetch')

Otherwise you will run into issues.

2 Comments

what kind of issues, care to expand?
@hjpotter92 You can read this in docs. But in general, if you already have some Resident objects in memory, this update also updated these objects in memory. Otherwise, these objects will be out of date, which can lead to errors. But, synchronize_session also is slow which is also not good

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.