Tahreem Iqbal
Tahreem Iqbal

Reputation: 1015

Using regroup in Django template

I'm receiving a JSON object that contains many objects and lists of objects etc. In one of those lists is Year list like this:

[{'Year': '2015', 'Status': 'NR', 'Month': 'Jan'
{'Year': '2014', Status': '', 'Month': 'Jan'}, 
{'Year': '2015', 'Status': '',Month': 'Feb'}, 
{'Year': '2014', Status': '', 'Month': 'Feb'}, 
{'Year': '2015', 'Status': '', Month': 'Sep'}, 
{'Year': '2014', 'Status': 'OK', 'Month': 'Sep'}, 
{'Year': '2015', 'Status': '', 'Month': 'Oct'}, 
{'Year': '2014', 'Status': 'OK', 'Month': 'Oct'}] 

I need to group this list by Year and display months according to their year. For example:

{"2015":[{"Month":"Jan", "Status":"NR"}, {"Month" : "Feb". "Status" :""}]

Right now, the code I'm using doesn't work the way I want it to, instead it repeats the years according to the number of months:

2015                                                
2014                                                
2015                                                
2014                                                
2015                                                
2014                                                
2015                                                
2014

This is the code:

{% regroup x.LstPaymentBehaviour by Year as yearList %} 
  {% for ym in yearList  %}
    <tr>
           <td><strong>{{ ym.grouper }}</strong></td>
    </tr>
  {% endfor %}

What am I missing?

Upvotes: 2

Views: 7724

Answers (1)

Termi
Termi

Reputation: 661

docs: https://docs.djangoproject.com/en/stable/ref/templates/builtins/#regroup

regroup expects ordered data in the first place. If all the items with same year are consecutive then you will get the desired output. So first sort your input data

{% regroup x.LstPaymentBehaviour|dictsort:'Year' by Year as yearList %} 

Upvotes: 6

Related Questions