[Django]-Django – show sums of a table of records

4👍

One word: Aggregation

Invoice_Line_Item.objects.filter(invNum=invoice).aggregate(Sum('itemPrice'))

https://docs.djangoproject.com/en/dev/topics/db/aggregation/

Another way is to store the total in Invoice and update it whenever you change a related Invoice_Line_Item

0👍

One more word: annotate.

from django.models import Sum

Invoice.objects.filter( .. ).annotate( InvTotal=Sum( 'invoice_line_number__itemPrice' ) ) 

InvTolal becomes a new attribute of Invoice object, you can use it in template the same way as invoiceNum or invoiceDate.

With this approach you do not have to pass any additional data structures to your template, only a QuerySet of Invoices.

Please note:
Argument of Sum is a string, which is a concatenation of the name of related model converted to lowercase, than double ‘_’, and than the name of a field in related model.

👤lesnik

Leave a comment