Django用不同的字段注释计数 [英] Django annotate count with a distinct field
问题描述
我有两个模型定义如下:
I have two models defined loosely like this:
class InformationUnit(models.Model):
username = models.CharField(max_length=255)
project = models.ForeignKey('Project')
...
class Project(models.Model):
name = models.CharField(max_length=255)
现在,在一个视图中,我想注释所有InformationUnits属于一个项目,所以我这样做:
Now, in a view, I want to annotate all the InformationUnits that belong to a project, so I do this:
p = Project.objects.all().annotate(Count('informationunit')
哪些工作只是ok
此外,我想知道,在每个项目,有多少不同的'用户名'参与
那就是计算在组成一个项目的InformationUnits中有多少个不同的用户名
我已经尝试了以下的,但它只是计数的信息单元,不管用户名:
which works just ok Furthermore, I want to know, in each project, how many distinct 'username' participate. That is, count how many distinct 'username' are there in the InformationUnits that compose one project. I have tried the following, but it simply counts the number of InformationUnit, regardless of the username:
p = Project.objects.all().annotate(Count('informationunit__username')
请注意,用户名不是一个对象,它是一个字符串。有没有干净的方法来做到这一点,或者我应该创建一个基于循环和意大利面条代码的更复杂的代码:P
Note that username is not an object, it is a string. Is there a clean way to do this or should I create a more complicated code based on loops and spaghetti code :P
非常感谢!
推荐答案
计数
可以采用 distinct
,如下所示:
Count
can take a distinct
argument, like so:
p = Project.objects.all().annotate(Count('informationunit__username',
distinct=True))
这似乎没有记录,但你可以在来源为Count。
This doesn't seem to be documented, but you can find it in the source for Count.
这篇关于Django用不同的字段注释计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!