繁体   English   中英

Django queryset SUM 正负值

[英]Django queryset SUM positive and negative values

我有一个将IntegerField命名为阈值的模型。 我需要的阈值的总和,无论负值。

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

什么是更快更合适的方法?

在 Django 中使用abs函数

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

尝试这个:

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])

我认为没有一种简单的方法可以使用 Django orm 进行计算。 除非你有性能问题,否则在 python 中进行计算没有任何问题。 您可以使用sum()abs()稍微简化您的代码。

votes = Vote.objects.all()
earning = sum(abs(v.vote_threshold) for v in votes) 

如果性能是一个问题,您可以使用原始 SQL

from django.db import connection

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

这个例子,如果你想在一个查询中求和负数和正数

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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM