2016-07-07 1 views
1

나는이 다음 모델 :장고 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 쿼리는 내가 지불 할 수있는 항목 목록과 지불 할 수있는 최대 금액을 제공합니다. 원시 SQL 대신 순수 ORM을 사용하여 동일한 쿼리를 수행 할 수 있습니까? 원시 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

, 환상적인 짧고 달콤한 매력처럼 작동합니다, 감사합니다! –