Django ORM 复杂查询
Django ORM complex query
我有以下型号:
class Invoice(models.Model):
amount = models.DecimalField()
date = models.DateTimeField()
class InvoiceItem(models.Model):
invoice = models.ForeignKey(Invoice)
description = models.CharField(max_length=256)
amount = models.DecimalField()
class PaymentDistribution(models.Model):
item = models.ForeignKey(invoiceItem)
amount = models.DecimalField()
select a.id,
a.amount,
a.amount-coalesce(sum(b.amount),0) as to_pay
from invoiceitems as a
left join paymentdistribution as b
on (a.id=b.invoiceitem_id)
group by a.id, a.amount
order by to_pay desc
这是一个简单的发票项目结构。我希望能够在多个项目之间分配付款并跟踪付款的分配。 SQL 查询为我提供了我可以支付的项目列表和我可以支付的最大金额。有没有办法使用纯 ORM 而不是原始 SQL 来执行相同的查询?我试图避免原始 SQL.
from django.db.models import F, Sum, Value as V
from django.db.models.functions import Coalesce
InvoiceItem.objects.values('id', 'amount').annotate(
to_pay=F('amount') - Coalesce(Sum('paymentdistribution__amount'), V(0))
).order_by('-to_pay')
文档:
我有以下型号:
class Invoice(models.Model):
amount = models.DecimalField()
date = models.DateTimeField()
class InvoiceItem(models.Model):
invoice = models.ForeignKey(Invoice)
description = models.CharField(max_length=256)
amount = models.DecimalField()
class PaymentDistribution(models.Model):
item = models.ForeignKey(invoiceItem)
amount = models.DecimalField()
select a.id,
a.amount,
a.amount-coalesce(sum(b.amount),0) as to_pay
from invoiceitems as a
left join paymentdistribution as b
on (a.id=b.invoiceitem_id)
group by a.id, a.amount
order by to_pay desc
这是一个简单的发票项目结构。我希望能够在多个项目之间分配付款并跟踪付款的分配。 SQL 查询为我提供了我可以支付的项目列表和我可以支付的最大金额。有没有办法使用纯 ORM 而不是原始 SQL 来执行相同的查询?我试图避免原始 SQL.
from django.db.models import F, Sum, Value as V
from django.db.models.functions import Coalesce
InvoiceItem.objects.values('id', 'amount').annotate(
to_pay=F('amount') - Coalesce(Sum('paymentdistribution__amount'), V(0))
).order_by('-to_pay')
文档: