#django
#django
Вопрос:
Я хотел бы вычислить ‘total’ для каждой строки, используя следующий код, он показывает только итоговую сумму в последней строке, а не в каждой строке.
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)
{% 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>
{% endfor %}
Ответ №1:
Вы можете попробовать что-то вроде этого:
class Invoice(models.Model):
date = models.DateField(default=timezone.now)
client = models.ForeignKey(Client,on_delete=models.CASCADE)
# Total field for each invoice
total = models.DecimalField(max_digits=20, decimal_places=2, default=0)
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)
# Overriding the save method to update invoice total for each new item
def save(self, *args, **kwargs):
self.invoice.total = round(self.price * self.quantity, 2)
self.invoice.save()
super().save(*args, **kwargs)
{% for product in object.invoiceitem_set.all %}
<tr>
<td>{{product.product}}</td>
<td>{{product.price}}</td>
<td>{{product.quantity}}</td>
<td>{{product.invoice.total}}</td>
</tr>
{% endfor %}