django分组,分明,统计

时间:2014-08-06 12:10:29

标签: python mysql django django-queryset

在Django中查询模型的等效语句

select distinct final_category, count(responders) 
from johnson_jnjusage 
where no_of_people_house = "4" and 
      child_age_group="0 to 12 months" and 
      city = "HYDERABAD" and 
      nursing_cnt = "2ND TIME MOTHER" and 
      bucket="BRAND PENETRATION" 
group by final_category;

谢谢

1 个答案:

答案 0 :(得分:0)

基于Django docs for aggregation,它可能看起来像这样:

from django.db.models import Count
Usage.objects.filter(no_of_people_house='4', city='HYDERABAD', nursing_cnt='2ND TIME MOTHER', bucket='BRAND PENETRATION').values('final_category').annotate(responders=Count('responders'))

filter,values和annotate子句的顺序非常重要,因为它定义了聚合的行为方式。