与django查询中的条件求和

时间:2018-01-23 12:51:30

标签: mysql django

我们想在django中查询此查询

SELECT sum(recommended='1') AS YES,sum(recommended='0') AS NO FROM `rating` WHERE applied_users = 32500 

我们不知道如何使用总和“= 1”

Rating.objects.filter(applied_id = 32500).aggregate(YES = Sum('recommended'))

2 个答案:

答案 0 :(得分:2)

在django中使用聚合与case,它将返回单个结果并带有注释,它将返回多个记录

https://docs.djangoproject.com/en/1.11/ref/models/conditional-expressions/

from django.db.models import Sum, Case, When, IntegerField

Rating.objects.filter(applied_id = 32500)
    .aggregate(
        yes=Sum(
            Case(
                When(recommended='1', then=1), 
                output_field=IntegerField()
            ) 
        ),
        no=Sum(
            Case(
                When(recommended=0,then=1),
                output_field=IntegerField()
            )
        )
    )

答案 1 :(得分:1)

首先请参阅:https://docs.djangoproject.com/en/1.11/ref/models/conditional-expressions/

    from django.db.models import Sum, Case, When, IntegerField

    OR 

    from django.db.models.aggregates import Sum
    from django.db.models.expressions import Case, When

    ratings = Rating.objects
.annotate(yes_count=Sum(Case(When(recommended='1', then=1),output_field=IntegerField())))
.annotate(no_count=Sum(Case(When(recommended='0', then=1),output_field=IntegerField())))
.filter(applied_id = 32500)