Django ORM, sum of multiple columns

萝らか妹 提交于 2019-12-18 07:21:09

问题


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.


回答1:


You can use F(), and with annotation:

Foo.objects.annotate(i_sum=F('i1') + F('i2')+ F('i3')).filter(i_sum=200)



回答2:


You can use extra

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


来源:https://stackoverflow.com/questions/43323724/django-orm-sum-of-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!