python - Django 聚合只计算真值

标签 python django aggregate

我正在使用聚合来获取一列 bool 值的计数。我想要真值的数量。

DJANGO 代码:

count = Model.objects.filter(id=pk).aggregate(bool_col=Count('my_bool_col')

这将返回所有行的计数。

SQL 查询应该是:

SELECT count(CASE WHEN my_bool_col THEN 1 ELSE null END) FROM <table_name>

这是我的实际代码:

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'),
)

感谢 Peter DeGlopper 建议使用 django-aggregate-if

解决方法如下:

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'),
)

最佳答案

针对 Django 1.10 进行了更新。您现在可以执行条件聚合:

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

更多信息:

关于python - Django 聚合只计算真值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25250490/

相关文章:

c# - 评估来自字符串的嵌套属性调用

python - 在列表中生成字符串元素的组合,将它们限制为特定的字符数量

python - 程序给出给定字符串中所有潜在替换的列表,需要过滤掉不按字母顺序排列的子字符串

python - Tkinter Entry 总是返回空字符串

python - django-cms:如何从与其关联的应用程序获取页面

c# - 使用聚合连接 linq 将结果放入 POCO

python - Django 模型没有将数据实时保存到数据库

python - celery 长时间不活动后意外关闭

Python Pandas : Sort and group by, 然后对第二列的两个连续行求和以获得第三列的特定值

r - 如何找到某些变量的总体