2016-07-07 72 views
1

我有以下型號:Django的ORM複雜的查詢

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。

回答

2
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') 

文檔:

+0

好極了,簡短而親切,就像一個魅力,謝謝! –