使用Django ORM过滤计数 [英] Filtering on the count with the Django ORM

查看:109
本文介绍了使用Django ORM过滤计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询,基本上是计数X的所有项目,并返回存在多于一个的项目,连同他们的计数。现在我有这个:

  Item.objects.annotate(type_count = models.Count(type))。filter type_count__gt = 1).order_by( -  type_count)

但是没有返回任何内容对于所有项目)。我做错了什么?



理想情况下,应该得到以下内容:

 类型
----
1
1
2
3
3
3

并返回:

 计数
-----------
1 2
3 3


解决方案

为了计算每种类型的出现次数,您必须按类型字段分组。在Django中,这是通过使用来获得该字段。所以,这应该工作:

  Item.objects.values('group')。annotate(
type_count = models .Count(type)
).filter(type_count__gt = 1).order_by( - type_count)


I have a query that's basically "count all the items of type X, and return the items that exist more than once, along with their counts". Right now I have this:

Item.objects.annotate(type_count=models.Count("type")).filter(type_count__gt=1).order_by("-type_count")

but it returns nothing (the count is 1 for all items). What am I doing wrong?

Ideally, it should get the following:

Type
----
1
1
2
3
3
3

and return:

Type, Count
-----------
1     2
3     3

解决方案

In order to count the number of occurrences of each type, you have to group by the type field. In Django this is done by using values to get just that field. So, this should work:

Item.objects.values('group').annotate(
     type_count=models.Count("type")
).filter(type_count__gt=1).order_by("-type_count")

这篇关于使用Django ORM过滤计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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