I want to get the sum of all values from items related to a certain object. In concrete, I have invoices with one or many items. Each item has a price and I want to calculate the sum of the prices for all the items of one invoice.
These are the essential parts of my models.py:
from django.db import models
from django.db.models import Sum
class Invoice(models.Model):
@property
def price(self):
return self.item_set.aggregate(Sum('price'))
class Item(models.Model):
invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=8, decimal_places=2)
The view.py is simple:
class InvoiceDetailView(DetailView):
model = Invoice
In my template invoice_detail.html
, {{ invoice.price }}
delivers something like
{'price__sum': Decimal('282.400000000000')}
So I added get('price__sum')
to the price property of the Invoice Model like that:
return self.item_set.aggregate(Sum('price')).get('price__sum')
The result actually is fine now, i.e. the template shows something like 282.400000000000
(which I still could style a bit), but I wonder, if that's the way to do something like that or if there is a better way?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…