[Django]-Django annotate count with a distinct field

207👍

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.

53👍

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()

15👍

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

9👍

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()

Leave a comment