我有一个应用程序,用户可以创建页面。我想运行一个简单的DB查询,返回有多少用户创建了超过2个页面。
这基本上就是我想要做的,但这当然不是正确的方法:
User.objects.select_related('page__gte=2').count()我遗漏了什么?
发布于 2011-06-30 03:05:41
您应该使用aggregates。
from django.db.models import Count
User.objects.annotate(page_count=Count('page')).filter(page_count__gte=2).count()发布于 2017-06-24 13:59:31
在我的例子中,我没有像other answer那样使用last .count(),它也工作得很好。
from django.db.models import Count
User.objects.annotate( our_param=Count("all_comments")).filter(our_param__gt=12)发布于 2021-04-04 05:17:55
在django.db.models方法中使用aggregate()函数!这非常有用,并且不会真正与其他注释聚合列相提并论。*在计算的最后一步使用aggregate(),它会将您的查询集转换为dict。
下面是我使用它们的代码片段。
cnt = q.values("person__year_of_birth").filter(person__year_of_birth__lte=year_interval_10)\
.filter(person__year_of_birth__gt=year_interval_10-10)\
.annotate(group_cnt=Count("visit_occurrence_id")).aggregate(Sum("group_cnt"))https://stackoverflow.com/questions/6525771
复制相似问题