Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3301618
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T20:46:10+00:00 2026-05-17T20:46:10+00:00

From time to time I have to write some simple summarized reports using Django.

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T20:46:10+00:00Added an answer on May 17, 2026 at 8:46 pm

    I figured it out, it can be done with iterators, no need for a template tag. The trick is to delay iteration one cycle.

    class GroupSummaryIterator(object):
        """GroupSummaryIterator(iterable, group_by, field_list)
    
    - Provides simple one level group/general summary for data iterables.
    - Suports both key and object based records
    - Assumes data is previously ordered by "group_by" property *before* use
    
    Parameters:
    ===========
      iterable: iterable data
      group_by: property or key name to group by
    field_list: list of fileds do sum
    
    Example:
    ======
    data =  [{'label': 'a', 'field_x': 1, 'field_c': 2},
             {'label': 'a', 'field_x': 3, 'field_c': 4},
             {'label': 'b', 'field_x': 1, 'field_c': 2},
             {'label': 'c', 'field_x': 5, 'field_c': 6},
             {'label': 'c', 'field_x': 1, 'field_c': 2}]
    
    s = GroupSummaryIterator(data, 'label', ['field_x', 'field_c'])
    for x,y in s:
         print y
         if x['group_changed']:
             print x['group'], 'summary:', x['group_summary']
    print 'general summary:', s.summary
    
        """
        def __init__(self, iterable, group_by, field_list):
            self.iterable = iterable
            self.group_by = group_by
            self.field_list = field_list
        def _a(self, obj, key):
            """Get property or key value"""
            if isinstance(key, basestring) and hasattr(obj, key):
                return getattr(obj, key)
            try:
                return obj[key]
            except:
                return None
        def _sum(self, item):
            if self.group_changed:
                self.cur_summary = dict()
            for field in self.field_list:
                value = self._a(item, field)
                if not value:
                    value = 0.0
                else:
                    value = float(value)
                if self.summary.has_key(field):
                    self.summary[field] += value
                else:
                    self.summary[field] = value
                if self.cur_summary.has_key(field):
                    self.cur_summary[field] += value
                else:
                    self.cur_summary[field] = value
        def _retval(self, item, summary):
            """If each item from the source iterable is itself an iterable, merge
            everything so you can do "for summ, a, b in i" where you would have
            done "for a, b in i" without this object."""
            if isinstance(item, dict):
                retval = (item,)
            else:
                try:
                    retval = tuple(item)
                except:
                    retval = (item,)
            return (dict(group_changed=self.group_changed, group=self.group, group_summary=summary),) + retval
        def __iter__(self):
            self.cur_group = None
            self.group = None
            self.finished = False
            self.group_changed = False
            self.cur_item = None
            self.last_item = None
            self.summary = dict()
            self.group_summary = dict()
            self.cur_summary = dict()
            for item in self.iterable:
                self.group = self.cur_group
                self.group_summary = self.cur_summary
                self.cur_group = self._a(item, self.group_by)
                self.group_changed = self.group and self.cur_group != self.group
                self.last_item = self.cur_item
                self.cur_item = item
                self._sum(item)
                if self.last_item is None:
                    continue
                yield self._retval(self.last_item, self.group_summary)
            if self.cur_item:
                self.group_changed = True
                yield self._retval(self.cur_item, self.group_summary)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have C# winforms application that needs to start an external exe from time
I have from the backend a time on the format 00:12:54 and I display
From time to time, a file that I'm interested in is modified by some
i have some WinForms app (Framework to develop some simple apps), written in C#.
I'm not a WinForms developer, but have been doing ASP.NET for quite some time.
I have a simple bean @Entity Message.java that has some normal properties. The life-cycle
I am attempting to pull some information from my tnsnames file using regex. I
I have been using Python for about a year now, coming from a mostly
From time to time I see an enum like the following: [Flags] public enum
From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.