在Django中我有一个看起来像这样的模型:
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']
但显然这不起作用:
无法将关键字“price_incl_vat”解析为字段。
知道如何实现这个目标吗?
答案 0 :(得分: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