2014-02-08 165 views
0

在Django中我有一個模型,它看起來像這樣:聚合@property子字段?

class Invoice(models.Model): 
    invoice_number = models.CharField(max_length=20) 

    @property 
    def total_invoice_amount(self): 
     return self.invoiceline_set.aggregate(Sum('price_incl_vat'))['price_incl_vat'] 


class InvoiceLine(models.Model): 
    invoice = models.ForeignKey(Invoice) 
    price_per_unit = models.DecimalField(decimal_places=4, max_digits=10) 
    unit = models.ForeignKey(staticdata.models.Unit) 
    amount = models.DecimalField(decimal_places=4, max_digits=10) 
    vat_percentage = models.DecimalField(decimal_places=4, max_digits=10) 

    # Calculated fields 
    @property 
    def price_excl_vat(self): 
     return self.price_per_unit * self.amount 

    @property 
    def vat_amount(self): 
     return self.price_excl_vat * self.vat_percentage/100 

    @property 
    def price_incl_vat(self): 
     return self.price_excl_vat + self.vat_amount 

我想有其是計算字段price_incl_vat的聚集和的總髮票金額。所以我構建total_invoice_amount這樣的:

@property 
def total_invoice_amount(self): 
    return self.invoiceline_set.aggregate(Sum('price_incl_vat'))['price_incl_vat'] 

但顯然不起作用:

無法解析keywork 'price_incl_vat' 到現場。

任何想法如何我可以實現這一目標?

回答

1

看來這是不能直接使用的聚合函數,所以我解決這樣說:

@property 
def total_invoice_amount(self): 
    total = 0 

    for invoice_line in self.invoiceline_set.all(): 
     total += invoice_line.price_incl_vat 

    return total