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

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 make a query top the table.

For instance, we write

exists = db.session.query(User.id).filter_by(name='davidism').first() is not None

to call query to query the table by User.id.

And we call filter_by to add additional filters by the name field value.

Then we call first to return the first value.

Conclusion

To check if row exists in table with Python Flask-SQLAlchemy, we can make a query top the table.