Django aggregate Count only True values
Updated for Django 1.10. You can perform conditional aggregation now:
from django.db.models import Count, Case, Whenquery_set.aggregate(bool_col=Count(Case(When(my_bool_col=True, then=1))))
More information at:
Update:
Since Django 1.10 you can:
from django.db.models import Count, Case, Whenquery_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:
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.