具有独立字段的 Django 注释计数

我有两个宽泛定义如下的模型:

class InformationUnit(models.Model):
username = models.CharField(max_length=255)
project = models.ForeignKey('Project')
...


class Project(models.Model):
name = models.CharField(max_length=255)

现在,在一个视图中,我想对属于一个项目的所有 InformationUnit进行注释,所以我这样做:

p = Project.objects.all().annotate(Count('informationunit')

效果还不错。

此外,我想知道,在每个项目中,有多少不同的 username参与。 也就是说,计算组成一个项目的 InformationUnit中有多少不同的 username。 我尝试了以下方法,但它只是计算 InformationUnit的数量,而不考虑 username:

p = Project.objects.all().annotate(Count('informationunit__username')

请注意,username不是一个对象,它是一个字符串。有没有一种简洁的方法来做到这一点,或者我应该创建一个更复杂的基于循环和意大利面条代码的代码: P

非常感谢!

69934 次浏览
Project.objects.all().annotate(Count('informationunit__username',
distinct=True))

Count can take a distinct argument, like so:

p = Project.objects.all().annotate(Count('informationunit__username',
distinct=True))

This doesn't seem to be documented, but you can find it in the source for Count.

If you just want to count the distinct values, you can use the distinct() and count() functions:

count = Project.objects.values('informationunit__username').distinct().count()

SQL SELECT field1, COUNT(DISTINCT(pk)) FROM project GROUP BY field1 ORDER BY NULL;

QuerySet

Project.objects.all().values(field1).annotate(count=Count('pk', distinct=True)).order_by()