django

Count branches in queryset


Django: 3.2

At a breakpoint I have such queryset:

<QuerySet [<UsingSemanticsLevelTwo: 2. Дубаец - 3. green_dubai_TR>, <UsingSemanticsLevelTwo: 2. Дубаец - 2. dubai_TR>, <UsingSemanticsLevelTwo: 1. Вас вызывает Дубай 1 - 4. dubai_COMP>]>

Model:

class UsingSemanticsLevelTwo(models.Model):
    branch = models.ForeignKey("clients.Branch",
                               on_delete=models.PROTECT,
                               blank=True,
                               null=True,
                               verbose_name=gettext("Branch"),
                               related_name="%(app_label)s_%(class)s_related",
                               related_query_name="%(app_label)s_%(class)ss", )

Problem

I want to count distinct branches in a queryset.

queryset.annotate(Count("branch"), distinct=True)

It blows up:

{TypeError}QuerySet.annotate() received non-expression(s): True.

How can I fix this?


Solution

  • The distinct is a keyword argument to Count not to annotate, hence your query should be:

    queryset.annotate(Count("branch", distinct=True))
    

    Instead of:

    queryset.annotate(Count("branch"), distinct=True)
    

    If there is a need to actually annotate a constant value it can be done by using a Value expression:

    from django.db.models import Value
    
    
    queryset.annotate(some_value=Value(True))
    

    Edit: If you just want to aggregate data you need to use aggregate [Django docs] instead of annotate (Annotate would aggregate on on the results of a group by, while aggregate simply will aggregate all rows):

    queryset.aggregate(Count("branch", distinct=True))['branch__count']