6

I have a question about how we can filter by SUM of multiple columns.

Example:

class Foo(models.Model):
    i1 = models.IntegerField()
    i2 = models.IntegerField()
    i3 = models.IntegerField()

And I need to filter objects where SUM of i1, i2, i3 is less then 200. I've tried achive it with:

Foo.objects.agregate(i_sum=Sum(i1,i2,i3)).filter(i_sum__lt=200) # error
Foo.objects.agregate(i_sum=Sum([i1,i2,i3])).filter(i_sum__lt=200) # error

Thanks.

2 Answers 2

14

You can use F(), and with annotation:

Foo.objects.annotate(i_sum=F('i1') + F('i2')+ F('i3')).filter(i_sum=200)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, it was really obvious. Sum is some kind of vertical operation but I needed horizontal.
Glad to help you
0

You can use extra

Foo.objects.extra(where=["i1 + i2 + i3 > 200"])

Comments

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.