Menu Close

How to check if row exists in table with Python Flask-SQLAlchemy?

Codeamend

Sometimes, we want to check if row exists in table with Python Flask-SQLAlchemy.

In this article, we’ll look at how to check if row exists in table with Python Flask-SQLAlchemy.

How to check if row exists in table with Python Flask-SQLAlchemy?

To check if row exists in table with Python Flask-SQLAlchemy, we can use the exists method.

For instance, we write

exists = db.session.query(
    db.session.query(User).filter_by(name="John Smith").exists()
).scalar() 

to call filter_by to select the entry in the user table with name column value 'John Smith'.

Then we call exists to see if any result is returned.

Conclusion

To check if row exists in table with Python Flask-SQLAlchemy, we can use the exists method.

Posted in Python

You can also read...