我有类 Invoice,它(简化)具有以下属性:
class Invoice(models.Model)
number = models.CharField(verbose_name="Number", max_length=16)
issue_date = models.DateTimeField(verbose_name="Issue date", default=datetime.now)
total = models.FloatField(verbose_name="Total", blank=True, null=True)
然后,我有类 InvoiceLine,它表示发票可以具有的行/行:
class InvoiceLine(models.Model):
invoice = models.ForeignKey(Invoice, verbose_name="Invoice")
description = models.CharField(verbose_name="Description", max_length=64)
line_total = models.FloatField(verbose_name="Line total")
InvoiceLine 是发票的内联,我想要实现的是,当在管理员中有人保存发票及其行(一个或多个)时,计算发票的总额。我试图通过覆盖方法保存来做到这一点:
class Invoice(models.Model)
number = models.CharField(verbose_name="Number", max_length=16)
issue_date = models.DateTimeField(verbose_name="Issue date", default=datetime.now)
total = models.FloatField(verbose_name="Total", blank=True, null=True)
def save(self, *args, **kwargs):
invoice_lines = InvoiceLine.objects.filter(invoice=self.id)
self.total = 0
for line in invoice_lines:
self.total=self.total+line.line_total
super(Invoice, self).save(*args, **kwargs)
问题是当我在 InvoiceLine 中添加元素时,第一次保存并调用函数时,内联 (InvoiceLine) 中的新元素尚未存储,所以当我这样做时InvoiceLine.objects.filter(invoice=self.id)
,它们不会被考虑在内。因此,唯一可行的方法是节省两次。我也试过:
def save(self, *args, **kwargs):
super(Invoice, self).save(*args, **kwargs)
invoice_lines = InvoiceLine.objects.filter(invoice=self.pk)
self.total = 0
for line in invoice_lines:
self.total=self.total+line.line_total
super(Invoice, self).save(*args, **kwargs)
但是结果是一样的。任何的想法?提前致谢!