[Answered ]-Totals/Subtotals in Django template

2👍

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>

Leave a comment