如何在Flask-SQLAlchemy中使用count() [英] How to use count() in Flask-sqlalchemy
问题描述
我正在协助一个使用flask-sqlalchemy的项目.我想要一个数据库查询来计算表中的记录数.我可以直接使用table.query.filter_by(condition).count()还是有什么需要我需要添加.请帮助我.我是初学者.谢谢!!
I am assisting a project which uses flask-sqlalchemy.I want a db query to count the number of records in the table.Can I use table.query.filter_by(condition).count() directly or is there anything that I need to add.Please assist me.I am a begineer.Thanks in advance!
推荐答案
给出的答案都没有专门针对 flask-sqlalchemy ,您将在其中使用给出的示例:
None of the given answers address flask-sqlalchemy specifically, where you would use exactly the example you gave:
Table.query.filter_by(condition).count()
您可以在没有过滤器的情况下执行 .count()
:
You can perform .count()
without filters:
Table.query.count()
您还可以使用M2M关系进行计数:
You can also count using M2M relationships:
ParentTable.children.count()
您可以直接在jinja模板中使用其中任何一个,例如:
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()
有点慢(尤其是在MySQL中,由于对子查询的处理不善),因此,您可以使用如下所示的自定义计数:
.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()
假定 db
是您的SQLAlchemy实例(即 db = SQLAlchemy(app)
).这很麻烦,但是可以节省一些大查询的开销.
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.
这篇关于如何在Flask-SQLAlchemy中使用count()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!