如何解决Django,如何计算每一行的总数
我想为每一行计算“总计”。使用以下代码,它仅显示最后一行,而不显示每行总计。以防万一我们有很多产品在此发票中。需要每种产品的总价(价格*数量)
class Invoice(models.Model):
date = models.DateField(default=timezone.now)
client = models.ForeignKey(Client,on_delete=models.CASCADE)
def total(self):
items = self.invoiceitem_set.all()
for item in items:
amount_due = (item.price * item.quantity)
return round(amount_due,2)
class InvoiceItem(models.Model):
invoice = models.ForeignKey('Invoice',on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
price = models.DecimalField(max_digits=20,decimal_places=2)
quantity = models.DecimalField(max_digits=20,decimal_places=2)
HTML
{% for product in object.invoiceitem_set.all %}
<tr>
<td>{{product.product}}</td>
<td>{{product.price}}</td>
<td>{{product.quantity}}</td>
<td>{{object.total}}</td>
</tr>
解决方法
它始终是相同的值,因为您要计算整个发票的总额并每次显示。因此,要将其分离出来,您可能需要尝试以下操作(如果我对您的理解正确):
向InvoiceItem类添加一个总函数:
class InvoiceItem(models.Model):
invoice = models.ForeignKey('Invoice',on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
price = models.DecimalField(max_digits=20,decimal_places=2)
quantity = models.DecimalField(max_digits=20,decimal_places=2)
def total(self):
return round(self.price * self.quantity,2)
然后html变成
{% for product in object.invoiceitem_set.all %}
<tr>
<td>{{product.product}}</td>
<td>{{product.price}}</td>
<td>{{product.quantity}}</td>
<td>{{product.total}}</td>
</tr>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。