Django annotate count with a distinct field

前端 未结 4 334
面向向阳花
面向向阳花 2020-11-29 05:49

I have two models defined loosely like this:

class InformationUnit(models.Model):
    username = models.CharField(max_length=255)
    project = models.Foreig         


        
相关标签:
4条回答
  • 2020-11-29 06:02

    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.

    0 讨论(0)
  • 2020-11-29 06:09

    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()
    
    0 讨论(0)
  • 2020-11-29 06:27

    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()
    
    0 讨论(0)
  • 2020-11-29 06:28
    Project.objects.all().annotate(Count('informationunit__username', 
                                         distinct=True))
    
    0 讨论(0)
提交回复
热议问题