I'm using aggregate to get the count of a column of booleans. I want the number of True values.
DJANGO CODE:
count = Model.objects.filter(id=pk).aggregate(bool_col=Count('my_bool_col')
This returns the count of all rows.
SQL QUERY SHOULD BE:
SELECT count(CASE WHEN my_bool_col THEN 1 ELSE null END) FROM <table_name>
Here is my actual code:
stats = Team.objects.filter(id=team.id).aggregate(
goals=Sum('statistics__goals'),
assists=Sum('statistics__assists'),
min_penalty=Sum('statistics__minutes_of_penalty'),
balance=Sum('statistics__balance'),
gwg=Count('statistics__gwg'),
gk_goals_avg=Sum('statistics__gk_goals_avg'),
gk_shutout=Count('statistics__gk_shutout'),
points=Sum('statistics__points'),
)
Thanks to Peter DeGlopper suggestion to use django-aggregate-if
Here is the solution:
from django.db.models import Sum
from django.db.models import Q
from aggregate_if import Count
stats = Team.objects.filter(id=team.id).aggregate(
goals=Sum('statistics__goals'),
assists=Sum('statistics__assists'),
balance=Sum('statistics__balance'),
min_penalty=Sum('statistics__minutes_of_penalty'),
gwg=Count('statistics__gwg', only=Q(statistics__gwg=True)),
gk_goals_avg=Sum('statistics__gk_goals_avg'),
gk_shutout=Count('statistics__gk_shutout', only=Q(statistics__gk_shutout=True)),
points=Sum('statistics__points'),
)
SELECT count(*) FROM <table name> WHERE my_bool_col = 1
? There's a simple expression for that query in Django, but either I don't understand what you're trying to do or you're doing this an unnecessarily hard way in SQL. – FiacreSum
on aBooleanField
? It's kind of a hack, but since the DB representation is either 1 or 0 the math works out right. Failing that, this third-party library looks relevant: pypi.python.org/pypi/django-aggregate-if – Fiacre