[Fixed]-Django aggregate Count only True values

9👍

Update:

Since Django 1.10 you can:

from django.db.models import Count, Case, When
query_set.aggregate(
    bool_col=Count(
        Case(When(my_bool_col=True, then=Value(1)))
    )
)

Read about the Conditional Expression classes

Old answer.

It seems what you want to do is some kind of “Conditional aggregation”. Right now Aggregation functions do not support lookups like filter or exclude: fieldname__lt, fieldname__gt, …

So you can try this:

django-aggregate-if

Description taken from the official page.

Conditional aggregates for Django queries, just like the famous SumIf and CountIf in Excel.

You can also first annotate the desired value for each team, I mean count for each team the ammount of True in the field you are interested. And then do all the aggregation you want to do.

30👍

Updated for Django 1.10. You can perform conditional aggregation now:

from django.db.models import Count, Case, When
query_set.aggregate(bool_col=Count(Case(When(my_bool_col=True, then=1))))

More information at:

👤James

6👍

Another Solution for count Bool is:

from django.db.models import Sum, IntegerField
from django.db.models.functions import Cast

Model.objects.filter(id=pk).annotate(bool_col=Sum(Cast('my_bool_col', IntegerField())))

Just convert False to 0 and True to 1, and then just Sum

👤Mijail

Leave a comment