计算并保存django中的发票总额



当我添加发票时,Total始终为0,但当我在没有任何更改的情况下更新时,它会用totalsubtotals()更新。我知道有很多计算,在我的情况下,总计算是在小计之前完成的。任何建议。

class Invoice(models.Model):
date = models.DateField(default=timezone.now)
client = models.ForeignKey('Client',on_delete=models.PROTECT)
total = models.DecimalField(default=0, max_digits=20, decimal_places=2)
def totalsubtotals(self):
items = self.invoiceitem_set.all()
total = 0
for item in items:
total += item.subtotal
return total
def save(self, *args, **kwargs):
self.total = self.totalsubtotals()
super(Invoice, self).save(*args, **kwargs)

class InvoiceItem(models.Model):
invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.PROTECT)
price = models.DecimalField(max_digits=20, decimal_places=2)
quantity = models.DecimalField(max_digits=20, decimal_places=2)
subtotal = models.DecimalField(default=0, max_digits=20, decimal_places=2)

def save(self, *args, **kwargs):
self.subtotal = self.price * self.quantity
super(InvoiceItem, self).save(*args, **kwargs)

在我看来,它就像你的"默认值=0";在您的InvoiceItem模型中,小计下是导致问题的原因,如果价格或数量有任何错误,则会存储默认值,并将0返回到您的Invoice模型。

我发现默认值也会使调试变得更加困难,所以我尽量只在值是可选的情况下使用它们,在发票的情况下,你不能订购任何数量的产品,也不能没有价格(0是一个数字(。输入中的错误会将DB中的值设置为Null(在Python的情况下为None(,然后你的默认值将小计设置为0。

当您尝试输入值时,删除默认值会导致错误,您可以根据错误消息更好地跟踪问题所在。

或者,在InvoiceItem的保存功能中,您可以尝试。。。

if self.price && self.quantity: (check that they're not Null/None)
self.subtotal = self.price * self.quantity
else:
raise ValueError('Incorrect values in price or subtotal')

最新更新