Django ORM, sum of multiple columns

2019-01-29 10:33发布

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条回答
仙女界的扛把子
2楼-- · 2019-01-29 11:11

You can use F(), and with annotation:

Foo.objects.annotate(i_sum=F('i1') + F('i2')+ F('i3')).filter(i_sum=200)
查看更多
萌系小妹纸
3楼-- · 2019-01-29 11:14

You can use extra

Foo.objects.extra(where=["i1 + i2 + i3 > 200"])
查看更多
登录 后发表回答