与GROUP BY相当于COUNT的Django [英] Django equivalent of COUNT with GROUP BY

查看:178
本文介绍了与GROUP BY相当于COUNT的Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Django 1.1有一些新的聚合方法。然而,我无法弄清楚以下查询的等价物:

  SELECT player_type,COUNT(*)FROM players GROUP BY player_type; 

是否可以使用Django 1.1的Model Query API,还是应该使用简单的SQL? p>

解决方案

如果您使用的是Django 1.1 beta(trunk):

  Player.objects.values('player_type')。order_by()。annotate(Count('player_type'))




  • values('player_type') - 仅包含 player_type field into GROUP BY 子句

  • order_by() - 排除可能导致不需要的字段包含在 SELECT GROUP BY 中的默认排序。


I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query:

SELECT player_type, COUNT(*) FROM players GROUP BY player_type;

Is it possible with Django 1.1's Model Query API or should I just use plain SQL?

解决方案

If you are using Django 1.1 beta (trunk):

Player.objects.values('player_type').order_by().annotate(Count('player_type'))

  • values('player_type') - for inclusion only player_type field into GROUP BY clause.
  • order_by() - for exclusion possible default ordering that can cause not needed fields inclusion in SELECT and GROUP BY.

这篇关于与GROUP BY相当于COUNT的Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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