Flask-SQLAlchemy检查表中是否存在行 [英] Flask-SQLAlchemy check if row exists in table
问题描述
我希望能够检查一行中是否存在表。如何修改一个查询来检查行是否存在:
db.session.query(User).filter_by(name ='John Smith')
我在使用SQLAlchemy,但似乎不符合Flask-SQLAlchemy的工作方式:
from sqlalchemy.sql import exists
print session.query(exists()。where(User.email =='...'))。scalar()
谢谢。
既然你只想看看用户是否存在,你不想查询整个对象。只是查询id,如果标量返回不是None,则存在。
exists = db.session.query(User.id ).filter_by(name ='davidism')。scalar()不是None
第二个查询显示也工作正常,Flask-SQLAlchemy没有做任何事情来阻止任何类型的查询,SQLAlchemy可以作出。
exists = db.session .query(db.exists()。where(User.name =='davidism'))。scalar()
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()
这篇关于Flask-SQLAlchemy检查表中是否存在行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!