简体   繁体   English

Django queryset SUM 正负值

[英]Django queryset SUM positive and negative values

I have a model which have IntegerField named as threshold.我有一个将IntegerField命名为阈值的模型。 I need to get total SUM of threshold value regardless of negative values.我需要的阈值的总和,无论负值。

vote_threshold

100

-200

-5

result = 305

Right now I am doing it like this.现在我正在这样做。

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

What is a faster and more proper way?什么是更快更合适的方法?

use abs function in django在 Django 中使用abs函数

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

try this:尝试这个:

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

I don't think there is an easy way to do the calculation using the Django orm.我认为没有一种简单的方法可以使用 Django orm 进行计算。 Unless you have performance issues, there is nothing wrong with doing the calculation in python.除非你有性能问题,否则在 python 中进行计算没有任何问题。 You can simplify your code slightly by using sum() and abs() .您可以使用sum()abs()稍微简化您的代码。

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

If performance is an issue, you can use raw SQL .如果性能是一个问题,您可以使用原始 SQL

from django.db import connection

cursor = connection.cursor()
cursor.execute("SELECT sum(abs(vote_theshold)) from vote")
row = cursor.fetchone()
earning = row[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']

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

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