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:
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:
- Is exposing a session's CSRF-protection token safe?
- Django does django have an automatic timestamp create/update field like cakephp?
- Django ALLOWED_HOSTS for Amazon ELB
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
- How does this Man-In-The-Middle attack work?
- How to render a Django form with RadioSelect without getting a checked radiobutton by default?
- Django with system timezone setting vs user's individual timezones