Django aggregate Count only True values
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:
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())))
False to 0 and
True to 1, and then just
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
It seems what you want to do is some kind of "Conditional aggregation". Right now
Aggregation functions do not support lookups like
exclude: fieldname__lt, fieldname__gt, ...
So you can try this:
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.