Flask-SQLAlchemy check if row exists in table

前端 未结 5 2045
耶瑟儿~
耶瑟儿~ 2020-12-05 02:17

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 woul

5条回答
  •  一整个雨季
    2020-12-05 02:57

    Wrap a .exists() query in another session.query() with a scalar() call at the end. SQLAlchemy will produce an optimized EXISTS query that returns True or False.

    exists = db.session.query(
        db.session.query(User).filter_by(name='John Smith').exists()
    ).scalar()
    
    SELECT EXISTS (SELECT 1 
    FROM user 
    WHERE user.name = ?) AS anon_1
    

    While it's potentially more expensive due to the subquery, it's more clear about what's being queried. It may also be preferable over db.exists().where(...) because it selects a constant instead of the full row.

提交回复
热议问题