使用Django模型选择COUNT个? [英] Select a COUNT using Django model?
问题描述
有人知道是否有一种方法可以仅选择与Django中的查询匹配的行数吗?我进行了一次搜索,将结果分为40组,但我也想显示结果总数.我可以使用len(Model.objects.filter(name__icontains = search))之类的东西,但是这似乎效率很低(因为我假设这会生成"SELECT * FROM model",然后生成所有结果)对象).有什么建议吗?
Does anyone know if there's a way to just select the number of rows matching a query in Django? I have a search I've written that splits results into sets of 40, but I'd like to display the total number of results as well. I could to something like len(Model.objects.filter(name__icontains=search)), but it seems like that would be grossly inefficient (since I'm assuming that would generate a "SELECT * FROM model" and then all of the resulting objects). Any suggestions?
推荐答案
有两种主要的处理方法:
There are two main ways to handle this:
- 使用 Django的count()QuerySet方法 —简单地将count()附加到适当的QuerySet的末尾
- 生成一个在QuerySet —聚合是指您通过汇总或聚合个对象的集合来获取值".参考:Django聚合文档
- Use Django's count() QuerySet method — simply append count() to the end of the appropriate QuerySet
- Generate an aggregate over the QuerySet — Aggregation is when you "retrieve values that are derived by summarizing or aggregating a collection of objects." Ref: Django Aggregation Documentation
上面的链接指向Django文档的适用部分.
The links above are to the applicable sections of Django's documentation.
这篇关于使用Django模型选择COUNT个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!