我正在使用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')))
答案 0 :(得分:0)
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