sqlalchemy exists for query

lestat picture lestat · Oct 4, 2011 · Viewed 53.7k times · Source

How do I check whether data in a query exists?

For example:

users_query = User.query.filter_by(email='[email protected]')

How I can check whether users with that email exist?

I can check this with

users_query.count()

but how to check it with exists?

Answer

Cito picture Cito · Nov 12, 2012

The following solution is a bit simpler:

from sqlalchemy.sql import exists

print session.query(exists().where(User.email == '...')).scalar()