如何在django模板中实现运行总计? [英] How can i implement a running total in django Template?
问题描述
我有一个看法,返回由sales_date分组的销售摘要,例如
[{'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}]
我已经在模板中完成了分组,并将其与html ul 和 li 标签可以根据sales_date给我一个很好的分组效果
我的模板分组是基于以下代码:
{%regroup salecursor by sale_date | date:j / m / Yas salelist%}
/ pre>
和
{{saleitem.grouper}
结果是:
05 / 10/2010
- item1名称 - 2
- item2名称 - 10
06/10/2010
- Item1 Name - 1
-
您如何获得每个组的运行总计,即组合应该共有12个,第二组共有1个,一些这样的效果;
05/10/2010
- item1名称 - 2
-
item2名称 - 10
共12
06/10/2010
-
Item1 Name - 1
总计1
感谢
Gath
什么?你不知道 running_total
过滤器?
只是在那里开玩笑。没有一个这样,但很容易写一个。这通过再次分组的列表到 sum
salesum
值。
#app_filters.py
@ register.filter
def running_total(sales_list):
return sum(d.get (sales)中的d('salesum')
您可以在模板中使用它: / p>
{%resroup salecursor by sale_date | date:j / m / Yas salelist%}
< ul>
{%在salelist%}
< li> {{sales.grouper}}
< ul>
{%for sales.list%}
< li> {{item.item}} - {{item.salesum}}< / li>
{%endfor%}
< li>总计:< b> {{sales.list | running_total}}< / b>< / li>
< / ul>
< / li>
{%endfor%}
< / ul>
I have a view that returns my sales summary grouped by sales_date e.g.
[{'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 have done the grouping inside the template, and combined it with html ul and li tags to give me a nice grouping effect based on the sale_date
My template grouping is based on this code:
{% regroup salecursor by sale_date|date:"j/m/Y" as salelist %}
and
{{ saleitem.grouper }
The result is:
05/10/2010
- item1 Name - 2
- item2 Name - 10
06/10/2010
- Item1 Name - 1
How do u get a running total for each group i.e. group one should have a total of 12 and the second group a total of 1 and have something of this effect;
05/10/2010
- item1 Name - 2
item2 Name - 10
Total 12
06/10/2010
Item1 Name - 1
Total 1
Thanks Gath
What? Don't you know of the running_total
filter?
Just kidding there. There isn't one such but it is pretty easy to write one. This is a bit inefficient as it traverses the grouped list again to sum
the salesum
values.
# 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 thus 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>
这篇关于如何在django模板中实现运行总计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!