2014-11-06 4 views
0

나는 IntegerField에 임계 값으로 명명 된 모델이 있습니다. 음수 값에 관계없이 전체적으로 SUM이 필요합니다.장고 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

왜 '수익'변수로 'vote_threshold'를 더하거나 뺍니다 !! –

+0

나는 긍정적 인 결과가 필요합니다. +10, -10 = 20 –

+0

내 편집 된 답변 확인 –

답변

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

내가 장고 ORM을 사용하여 계산을 할 수있는 쉬운 방법이라고 생각하지 않습니다. 퍼포먼스 문제가 없다면, 파이썬에서 계산을하는 것은 잘못된 것이 아닙니다. 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

예 성능 문제가 있습니다. –

관련 문제