【问题标题】:Calculate and save the total of an invoice in django在 django 中计算并保存发票总额
【发布时间】:2021-03-22 06:19:47
【问题描述】:

当我添加发票时,总计始终为 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)

【问题讨论】:

    标签: django django-models django-views django-signals


    【解决方案1】:

    在我看来,您的 InvoiceItem 模型中小计下的“默认 = 0”是导致问题的原因,如果价格或数量有任何错误,则存储默认值,将 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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多