Django:在单个查询中对两个不同数据集的字段进行聚合(求和)

时间:2018-04-23 13:57:24

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

我正在使用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')))

2 个答案:

答案 0 :(得分:0)

您可以使用conditional expression

     Query query = QueryFactory.create(queryString);      
     QueryExecution qexec = QueryExecutionFactory.create(query, model);          
     Model m = qexec.execConstruct(model);     
     System.out.println(m.toString());
     model.close();

答案 1 :(得分:0)

这应该可以在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