1

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?

markwalker_
  • 12,078
  • 7
  • 62
  • 99
Lax_Sam
  • 1,099
  • 2
  • 14
  • 32

1 Answers1

3

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555