Django中的COUNT(id)而不是COUNT(*)

时间:2016-09-06 14:48:39

标签: django postgresql django-models django-pagination

我正在为包含许多字段的模型分页列表视图,因此执行MyModel.objects.filter('some filter').count()需要花费大量时间,因为在SQL级别上运行

SELECT COUNT(*) FROM mytable

而不是:

SELECT COUNT(id) FROM mytable

即使我明确写了

MyModel.objects.only('id').count() 

如何让Django在COUNT(id)上运行.count()

更新

我正在使用PostgreSQL。

2 个答案:

答案 0 :(得分:0)

尝试使用聚合查询:

from django.db import models
MyObject.objects.all().aggregate(models.Count('id'))['id__count']

答案 1 :(得分:0)

let string = textView.text.substringWithRange(Range<String.Index>(start: textView.text.startIndex, end: textView.text.startIndex.advancedBy(779)))// your <779 string let size = string.sizeWithAttributes([NSFontAttributeName:yourFont]) let point = CGPointMake(0, size.height) scrollView.setContentOffset(point, animated:true) 大致相当于:

COUNT(id)

这将增加计算表字段的额外步骤,而MyModel.objects.exclude(id=None).count()

不是这种情况