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?
It returns exactly one result or raise an exception. It applies one or more ORDER BY criterion to the query and returns the newly resulting Query. It performs a bulk update query and updates rows matched by this query in the database.
all() will return all records which match our query as a list of objects.
The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.
The following solution is a bit simpler:
from sqlalchemy.sql import exists print session.query(exists().where(User.email == '...')).scalar()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With