Django queryset SUM正负值

时间:2014-11-06 12:56:04

标签: python django

我有一个名为阈值的 IntegerField 的模型。 无论负值如何,我都需要获得阈值总<<>> SUM 。

vote_threshold

100

-200

-5

result = 305

现在我这样做。

earning = 0
result = Vote.objects.all().values('vote_threshold')
            for v in result:
                if v.vote_threshold >  0:
                    earning += v.vote_threshold
                else:
                    earning -= v.vote_threshold

什么是更快更正确的方式?

4 个答案:

答案 0 :(得分:1)

在Django中使用abs函数

from django.db.models.functions import Abs
from django.db.models import Sum
<YourModel>.objects.aggregate(s=Sum(Abs("vote_threshold")))

答案 1 :(得分:0)

试试这个:

objects = Vote.objects.extra(select={'abs_vote_threshold': 'abs(vote_threshold)'}).values('abs_vote_threshold')
earning = sum([obj['abs_vote_threshold'] for obj in objects])

答案 2 :(得分:0)

我认为使用Django orm进行计算并不容易。除非遇到性能问题,否则在python中进行计算没有任何问题。您可以使用sum()abs()

轻微简化代码
votes = Vote.objects.all()
earning = sum(abs(v.vote_threshold) for v in votes) 

如果性能问题,您可以use raw SQL

from django.db import connection

cursor = connection.cursor()
cursor.execute("SELECT sum(abs(vote_theshold)) from vote")
row = cursor.fetchone()
earning = row[0]

答案 3 :(得分:0)

This one example, if you want to sum negative and positive in one query

select = {'positive': 'sum(if(value>0, value, 0))', 
          'negative': 'sum(if(value<0, value, 0))'}
summary = items.filter(query).extra(select=select).values('positive', 'negative')[0]
positive, negative = summary['positive'], summary['negative']