Skip to content
Advertisement

how to do a subquery or filter in a condition met by a previous query correctly

Im using python, flask and sqlalchemy have the query below:

query = db.session.query(model.Foo1, model.Foo2).join(model.Foo1, model.Foo1.id == model.Foo2.name_id).first()

Now let’s assume that i want to search for the condition Foo1.id != 2 but still make sure that i meet the condition of the query above, what would be the best way to achieve that (i am trying to learn how to do subquery or filter in another query properly)

Thank for the help

Advertisement

Answer

For Foo1.id != 2 You don’t need a subquery. Filter is enough.

result = db.session.query(model.Foo1, model.Foo2)
         .join(model.Foo1, model.Foo1.id == model.Foo2.name_id)
         .filter(model.Foo1.id != 2).all()

This will return a list of all rows that have ids not equal to 2

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement