Django annotate count with a distinct field
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()
Project.objects.all().annotate(Count('informationunit__username',
distinct=True))
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()
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.