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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

So this condition is similar to checking whether MyModel.toss_winner = MyModel.winner and MyModel.win_by_runs = 0?
@Laxman: yes. We thus count the number of MyModel records, for which that condition holds.
Ok. One last question. How to check not equal to in django? Because according to my understanding there is no '!=' operator in django.
To check win_by_runs != 0 what should be the operator?
@Laxman: sorry, the arguments indeed should be swapped, so MyModel.objects.filter(~Q(win_by_runs=0), toss_winner=F('winner')).count().
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.