From time to time I have to write some simple summarized reports using Django.
First I tried using Django ORM aggregates and interleaving results, but it can get a bit messy and I loose all the ORM laziness - just doesn't feels right.
Lately I wrote a generic iterator class that can group/summarize a dataset. In the view it works like:
s_data = MyIterator(dataset, group_by='division', \
sum_fields=[ 'sales', 'travel_expenses'])
In the template it works like:
{% for g, reg in s_data %}
{% if g.group_changed %}
<tr><!-- group summary inside the loop -->
<td colspan="5">{{ g.group }} Division</td>
<td>{{ g.group_summary.sales }}</td>
<td>{{ g.group_summary.travel_expenses }}</td>
</tr>
{% endif %}
<tr><!-- detail report lines -->
<td>{{ reg.field }}<td>
<td>{{ reg.other_field_and_so_on }}<td>
...
</tr>
{% endfor %}
<tr><!-- last group summary -->
<td colspan="5">{{ s_data.group }} Division</td>
<td>{{ s_data.group_summary.sales }}</td>
<td>{{ s_data.group_summary.travel_expenses }}</td>
</tr>
<tr>
<td colspan="5">Total</td>
<td>{{ s_data.summary.sales }}</td>
<td>{{ s_data.travel_expenses }}</td>
</tr>
I think it is a lot more elegant than my previous approach but having to repeat the code for the last group summary violates the DRY principle.
I had a look at "Geraldo reporting" but it was not "love at the first sight".
Why there is no group/summary template tag, should I write one?