[英]django count a field but group by another
So I am using django with mysql, and I have a model MyModel
, which contains some items with None
on the region
field. 因此,我将django与mysql一起使用,并且我有一个模型
MyModel
,其中包含一些在region
字段中为None
项目。 When I run this: 当我运行这个:
results = MyModel.objects.all()\
.values('region')\
.annotate(total=Count('region'))
it returns the grouping correctly, but one is {'None': 0}
, which is incorrect, because there are some items with region
field equal to None
. 它会正确返回分组,但是一个是
{'None': 0}
,这是不正确的,因为有些项目的region
字段等于None
。
Now, if I were using mysql
then I could group this with: 现在,如果我使用的是
mysql
则可以使用以下命令将其分组:
select region, count(id) from model_table group by region;
which returns the solution I want | NULL | 5 |
哪个返回我想要的解决方案
| NULL | 5 |
| NULL | 5 |
. 。
How can I achieve this from django? 我如何从Django实现这一目标?
You actually already wrote the answer in your question. 您实际上已经在问题中写下了答案。 As far as I know, COUNT in SQL excludes certain falsey values like NULL.
据我所知,SQL中的COUNT排除了某些虚假值,例如NULL。 So if you want to count the falsey values as well, you use another field to perform the aggregate, just like you did in your SQL statement where you used the 'id' field.
因此,如果您还想计算假值,则可以使用另一个字段执行汇总,就像在使用“ id”字段的SQL语句中所做的一样。 On that note, all you need to do is to perform COUNT on 'id'.
需要注意的是,您要做的就是对“ id”执行COUNT。 Change your code to something like this:
将您的代码更改为如下所示:
results = MyModel.objects.all()\
.values('region')\
.annotate(total=Count('id'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.