Lax_Sam
Lax_Sam

Reputation: 1139

Django sum on query set

I have a queryset in django with condition as follows:

query_set = MyModel.objects.annotate(TWWByRuns=(
    Case(
        When(Q(toss_winner=F('winner')) & Q(win_by_runs=0), then=1),
        output_field=FloatField(), default=0)
    )
).values('TWWByRuns')

I would like to use django built-in sum function to add whenever the value in the query_set equals to 1 as in when then=1. I know to use the sum function without conditionals but here since I have condition where should I use the sum function in this query_set?

Upvotes: 1

Views: 81

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476544

In this specific case, it makes more sense to count:

MyModel.objects.filter(toss_winner=F('winner'), win_by_runs=0).count()

We here thus simply check how many MyModel records satisfy the given condition.

Upvotes: 3

Related Questions