Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

How to provide a negative condition in Case/When clause while using Django ORM?

I am using Django 1.8. I am making a conditional aggregate where a Case statement inside Sum looks like this:

Sum(Case(When(x='ABC', then=F('some_field')), default=0))

If I want to say x should be anything but not 'ABC' then how do I negate this condition. Will ~Q work in this scenario ?

Upvotes: 1

Views: 1846

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52093

Yes, you are on the right track. "Not equal" conditions can be created using Q objects:

Sum(Case(When(~Q(x='ABC'), then=F('some_field')), default=0))

Upvotes: 5

Related Questions