如何在django中查询为GROUP BY? [英] How to query as GROUP BY in django?

查看:413
本文介绍了如何在django中查询为GROUP BY?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查询一个模型,

Members.objects.all()

,并返回说

Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop

我想要的是,知道最好的Django方式,将
a group_by查询发送到我的数据库,如同

What i want is, to know the best Django way to fire a group_by query to my db, as like,

Members.objects.all().group_by('designation')

当然不行。
我知道我们可以在django / db / models / query.py,
上做一些技巧,但我只是好奇地知道如何在没有修补的情况下执行。

Which doesn't work of course. I know we can do some tricks on "django/db/models/query.py", but i am just curious to know how to do it without patching.

推荐答案

如果你想做聚合,你可以使用 ORM的聚合功能

If you mean to do aggregation you can use the aggregation features of the ORM:

from django.db.models import Count
Members.objects.values('designation').annotate(dcount=Count('designation'))

这将产生一个类似于

SELECT designation, COUNT(designation) AS dcount
FROM members GROUP BY designation

,输出的形式为



and the output would be of the form

[{'designation': 'Salesman', 'dcount': 2}, 
 {'designation': 'Manager', 'dcount': 2}]

这篇关于如何在django中查询为GROUP BY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆