None of the given answers address flask-sqlalchemy specifically, where you would use exactly the example you gave:
Table.query.filter_by(condition).count()
You can perform .count()
without filters:
Table.query.count()
You can also count using M2M relationships:
ParentTable.children.count()
And you can use any of these directly in your jinja templates like:
{{ Table.query.filter_by(condition).count() }}
Bonus points (for the performance minded):
.count()
is a bit slow (especially with MySQL, thanks to a poor handling of subqueries), so instead, you can use a custom count that looks like this:
db.session.execute(Table.query.filter_by(condition).statement.with_only_columns([func.count()]).order_by(None)).scalar()
That’s assuming db
is your SQLAlchemy instance (ie, db = SQLAlchemy(app)
). It’s a mouthful, but it will save you a little bit of overhead on big queries.