簡體   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