Django聚合仅计数True值

Pie*_*tro 10 python django aggregate

我正在使用聚合来计算一列布尔值.我想要真值的数量.

DJANGO代码:

count = Model.objects.filter(id=pk).aggregate(bool_col=Count('my_bool_col')
Run Code Online (Sandbox Code Playgroud)

这将返回所有行的计数.

SQL QUERY应该是:

SELECT count(CASE WHEN my_bool_col THEN 1 ELSE null END) FROM <table_name>
Run Code Online (Sandbox Code Playgroud)

这是我的实际代码:

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'),
)
Run Code Online (Sandbox Code Playgroud)

感谢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'),
)
Run Code Online (Sandbox Code Playgroud)

Tri*_*Nhu 25

更新了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))))
Run Code Online (Sandbox Code Playgroud)

更多信息:

  • 这个答案是更新的,是第三方django-aggregate-if模块的更好选择 (2认同)

Ray*_*nda 7

更新:

从 Django 1.10 开始,您可以:

from django.db.models import Count, Case, When
query_set.aggregate(
    bool_col=Count(
        Case(When(my_bool_col=True, then=Value(1)))
    )
)
Run Code Online (Sandbox Code Playgroud)

阅读条件表达式类

旧答案。

看来您想要做的是某种“条件聚合”。现在Aggregation函数不支持像filter或这样的查找exclude:fieldname__lt, fieldname__gt, ...

所以你可以试试这个:

django-aggregate-if

描述取自官方页面。

Django 查询的条件聚合,就像 Excel 中著名的 SumIf 和 CountIf。

您还可以先为每个团队注释所需的值,我的意思是为每个团队计算True您感兴趣的领域的数量。然后做所有你想做的聚合


小智 6

count Bool 的另一个解决方案是:

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())))
Run Code Online (Sandbox Code Playgroud)

只需转换False为 0 和True1,然后只需Sum