背景:
想要使用django中orm实现以下sql语句的功能:
SELECT ptype, COUNT(ptype) AS dcount FROM people GROUP BY ptype
使用django的ORM聚合功能
from django.db.models import Count People.objects.values('ptype').annotate(dcount=Count('ptype'))
上述查询等同于sql语句:
SELECT ptype, COUNT(ptype) AS dcount FROM people GROUP BY ptype
返回的结果是:
[{'ptype': 'studen', 'dcount': 10}, {'ptype': 'teacher', 'dcount': 2}]
还没有留言,还不快点抢沙发?