【问题标题】:Django, how to calculate the total of each lineDjango,如何计算每行的总数
【发布时间】:2020-08-24 21:56:17
【问题描述】:

我想计算每一行的“总数”。使用下面的代码,它只显示最后一行的总数,而不是每一行的总数。如果我们在这张发票中有很多产品。需要每种产品的总和(价格*数量)

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>

【问题讨论】:

    标签: django django-models django-views django-templates


    【解决方案1】:

    它始终是相同的值,因为您要计算整个发票的总和并每次都显示。因此,要将其分开,您可能需要尝试以下操作(如果我理解正确的话):

    在 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>
    

    【讨论】:

    • 如果我想在“产品”表上添加另一个 {{product.weight}} 并且我希望它计算总重量 {{product .total_weight}} (total_weight=weight*quantity)
    猜你喜欢
    • 2021-05-23
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多