【问题标题】:Django: Aggregate (sum) of a field on two different set of data in a single queryDjango:在单个查询中聚合(总和)两个不同数据集的字段
【发布时间】:2018-10-03 14:42:49
【问题描述】:

我正在使用 Django 1.6。 我的模型看起来像:

Class Transaction(models.Model):
    type = models.CharField(max_length=255, db_index=True)
    amount = models.DecimalField(decimal_places=2, max_digits=10, default=0.00)

我的交易很少,其中很少是贷方,其他是借方(由类型列确定)。我需要检查所有交易的余额,即(借方 - 贷方)

目前,我可以使用以下 2 个查询来做到这一点:

debit_amount=Transaction.objects.fitler(type='D').aggregate(debit_amount=Sum('amount'))['debit_amount']
credit_amount=Transaction.objects.fitler(type='C').aggregate(credit_amount=Sum('amount'))['credit_amount']
balance = debit_amount - credit_amount

我看起来像:

Transaction.objects.aggregate(credit=Sum('amount', filter=Q(type='C')), debit=Sum('amount', filter=Q(type='D')))

【问题讨论】:

    标签: django postgresql django-models orm django-queryset


    【解决方案1】:

    这在 django 2.0 中应该是可能的 (https://docs.djangoproject.com/en/2.0/ref/models/conditional-expressions/#case)

    totals = Transaction.objects.aggregate(
        credit=Sum('amount', filter=Q(type='C')),
        debit=Sum('amount', filter=Q(type='D'))
    )
    total = totals.credits - totals.debit
    

    【讨论】:

      【解决方案2】:

      您可以使用conditional expression

      from django.db.models import *
      result = Transaction.objects.aggregate(
          credit=Sum(Case(
              When(Q(tye='C'), then=F('amount')),
              output_field=IntegerField(),
              default=0
          )),
          debit=Sum(Case(
              When(Q(tye='D'), then=F('amount')),
              output_field=IntegerField(),
              default=0
          )),
      )
      
      balance = result['debit'] - result['credit']
      

      【讨论】:

        猜你喜欢
        • 2012-08-23
        • 1970-01-01
        • 2014-02-23
        • 2016-10-30
        • 2012-05-04
        • 1970-01-01
        • 1970-01-01
        • 2021-02-06
        • 1970-01-01
        相关资源
        最近更新 更多