I have a Flask application which uses Flask-SQLAlchemy to connect to a MySQL database.
I would like to be able to check whether a row is present in a table. How would I modify a query like so to check the row exists:
db.session.query(User).filter_by(name='John Smith')
I found a solution on this question which uses SQLAlchemy but does not seem to fit with the way Flask-SQLAlchemy works:
from sqlalchemy.sql import exists
print session.query(exists().where(User.email == '...')).scalar()
Thanks.
解决方案
Since you only want to see if the user exists, you don't want to query the entire object. Just query the id, it exists if the scalar return is not None.
exists = db.session.query(User.id).filter_by(name='davidism').scalar() is not None
The second query you showed also works fine, Flask-SQLAlchemy does nothing to prevent any type of query that SQLAlchemy can make.
exists = db.session.query(db.exists().where(User.name == 'davidism')).scalar()