Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Annotate Sum

I'm trying to get a simple sum for a column with several rows in a queryset. My direct question is (a) how do I set get_queryset() to include a sum of a column and (b) how do I access that element in a template? Following this question:

#models.py
class ItemPrice( models.Model ):
    price = models.DecimalField ( max_digits = 8, decimal_places=2 )
    ....

There are two answers provided - one using the .aggregate() method which I don't believe returns a queryset and .annotate() method which I believe appends an item to the queryset.

So, I would have expected that the following would add another item to the object list in this view:

#views.py
def get_queryset(self):
    # generate table and filter down to a subquery.
    queryset = ItemPrice.objects.filter(<some_filter>)
    # sum the price for each row in the subquery.
    queryset = queryset.annotate(totals=Sum('price'))
    return queryset

Then in the the Template, I would be able to iterate through the object list like this:

#template.html
{% for item in object_list %}
    {{ item }}
{% endfor %}

With the expectation that one of the items (the last item?) would be price_sum and that the balance could be accessed as price_sum.price.

However, when i add the following to my template, I get the prices for each line item - no summation.

{% for item in object_list %}
    {{ item.totals }}
{% endfor %}

But, I can't access the item. I don't know if the problem is the view modification of the get_queryset() or if it's in the template?

like image 885
Bill Armstrong Avatar asked Jan 28 '23 03:01

Bill Armstrong


1 Answers

if you want to add data to the template

queryset = ItemPrice.objects.filter(<your_filter>)
totals = queryset.aggregate(sum=Sum('price').get('sum')

context  = {
    'object_list': queryset,
    'totals': totals,
}
render(request, '<name_of_your_template>.html', context)

and in your template

{% for item in object_list %}
    # price of item
    {{ item.price }}
{% endfor %}
# total price
{{ totals }}
like image 72
Andrey Berenda Avatar answered Jan 31 '23 10:01

Andrey Berenda