Django模板中的总计/小计 [英] Totals/Subtotals in Django template
问题描述
我很难解决一个简单的问题。
I'm having difficulty wrapping my head around a simple problem. How do you calculate totals and subtotals in a django template?
假设我要生成客户订单报告,例如:
Let's say I want to generate a report of customer's orders, something like:
Desired Report Output
Customer1
1 Widgets $ 2
1 Bobbins $ 1
Subtotal $ 3
Customer2
2 Widgets $ 4
2 Bobbins $ 2
Subtotal $ 6
TOTAL $ 9
假设我们在我们的视图中填充了字典
Let's assume we populate a dictionary in our view
orgs = {}
orgs['Customer1'] = [
{ 'qty': 1, 'descr' : 'Widgets', 'price': 2 },
{ 'qty': 1, 'descr' : 'Bobbins', 'price': 1 },
]
...
和类似的模板:
{% for org,orders in orgs.items %}
<p>{{ org }}
{% for order in orders %}
<ul>
<li>{{ order.qty }}</li>
<li>{{ order.descr }}</li>
<li>{{ order.price }}</li>
</ul>
...
关于如何计算总计/小计的任何想法?
Any idea on how to calculate totals/subtotals?
我理解基本的建议是在视图中执行此操作,但我不知道如何将其放入组织命令中。根据django docs( https://docs.djangoproject.com/en/dev/ref/templates/api/#variables-and-lookups )。
I understand the basic recommendation is to do this in the view, but I can't figure out how to put this in the orgs dict. And trying to use a parallel data structure does not seem to be possible according to the django docs (https://docs.djangoproject.com/en/dev/ref/templates/api/#variables-and-lookups).
有什么想法吗?
推荐答案
不是组织密钥的值是词典列表,而是一本字典,其中一个键称为 orders
,另一个键称为小计
Instead of the organization key having a value that's a list of dictionaries, have it be a dictionary that has one key called orders
and another key called subtotal
如果传入了组织词典,那么您将如何更改它。
If the org dictionary is passed in, here's how'd you change it.
total = 0
for org in orgs:
orders = orgs[org]
subtotal = sum(order['qty']*order['price'] for order in orders)
total += subtotal
orgs[org] = {'orders': orders, 'subtotal': subtotal}
现在在模板中,您将执行以下操作:
Now in your template you'd do the following:
{% for org,org_data in orgs.items %}
<p>{{ org }}
{% for order in org_data.orders %}
<ul>
<li>{{ order.qty }}</li>
<li>{{ order.descr }}</li>
<li>{{ order.price }}</li>
</ul>
{% endfor %}
Subtotal: {{ org_data.subtotal }}
</p>
{% endfor %}
<p>Total: {{total}}</p>
这篇关于Django模板中的总计/小计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!