user590028
user590028

Reputation: 11730

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 },
    ]
...

And a template like this:

{% 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?

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).

Any ideas?

Upvotes: 1

Views: 2193

Answers (1)

schillingt
schillingt

Reputation: 13731

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>

Upvotes: 2

Related Questions