How can I implement the current amount in a django template?

I have a view that returns my sales summary, grouped by sales_date, for example.

[{'sale_date':datetime.datetime(2010,10,5,0,0), 'salesum':2, 'item':1}, {'sale_date':datetime.datetime(2010,10,5,0,0), 'salesum':10,'item':3}, {'sale_date':datetime.datetime(2010,10,6,0,0), 'salesum':1, 'item':1}] 

I did grouping inside the template and combined it with html ul and li tags to give me a nice grouping effect based on sales_date

My template grouping is based on this code:

 {% regroup salecursor by sale_date|date:"j/m/Y" as salelist %} 

and

 {{ saleitem.grouper } 

Result:

10/10/2010

  • item1 Name - 2
  • item2 Name - 10

10/10/2010

  • Item1 Name - 1

How to get the total amount for each group, that is, the group should have a total of 12, and the second - only 1 and have some of this effect;

10/10/2010

  • item1 Name - 2
  • item2 Name - 10

    Total 12

10/10/2010

  • Item1 Name - 1

    Total 1

Thanks gough

+4
source share
1 answer

What? You do not know about the filter running_total ?

Just kidding. There is not one such, but it is quite easy to write. This is a bit inefficient as it again moves the grouped list to the sum the salesum value.

 # app_filters.py @register.filter def running_total(sales_list): return sum(d.get('salesum') for d in sales_list) 

And you can use it this way in your template:

 {% regroup salecursor by sale_date|date:"j/m/Y" as salelist %} <ul> {% for sales in salelist %} <li>{{ sales.grouper }} <ul> {% for item in sales.list %} <li>{{ item.item }} - {{ item.salesum }}</li> {% endfor %} <li>Total: <b>{{ sales.list|running_total }}</b></li> </ul> </li> {% endfor %} </ul> 
+10
source

All Articles