Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy exists for query

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?

like image 637
lestat Avatar asked Oct 04 '11 10:10

lestat


People also ask

What does SQLAlchemy query return?

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.

What does query all () return?

all() will return all records which match our query as a list of objects.

What is subquery in SQLAlchemy?

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.


1 Answers

The following solution is a bit simpler:

from sqlalchemy.sql import exists  print session.query(exists().where(User.email == '...')).scalar() 
like image 122
Cito Avatar answered Sep 30 '22 17:09

Cito