【问题标题】:Django queryset SUM positive and negative valuesDjango 查询集 SUM 正负值
【发布时间】:2015-01-02 23:50:17
【问题描述】:

我有一个具有 IntegerField 命名为阈值的模型。 无论负值如何,我都需要获得阈值的总 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

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

【问题讨论】:

  • 为什么用earning变量加减vote_threshold!!?
  • 我需要结果为阳性。 +10 , -10 = 20
  • 检查我编辑的答案。

标签: python django


【解决方案1】:

在 django 中使用 abs 函数

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      【解决方案3】:

      我认为没有一种简单的方法可以使用 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]
      

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 2011-08-12
          • 2023-04-07
          • 2019-02-26
          • 1970-01-01
          • 1970-01-01
          • 2018-04-17
          • 2020-01-18
          • 2019-07-01
          • 2013-06-22
          相关资源
          最近更新 更多