2014-11-06 55 views
0

我有一個模型,它有IntegerField命名爲閾值。 無論負值如何,我都需要獲得總數爲SUM的閾值。Django queryset 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 

什麼是更快更正確的方法?

+0

你爲什麼用'earning'變量加減'vote_threshold' !!? – 2014-11-06 13:06:56

+0

我需要結果爲正面。 +10,-10 = 20 – 2014-11-06 13:11:24

+0

檢查我編輯的答案。 – 2014-11-06 13:24:11

回答

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

是有性能問題。 – 2014-11-10 05:40:05