Using regroup in Django template
<p>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:</p>

<pre><code>[{'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'}] 
</code></pre>

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

<pre><code>{"2015":[{"Month":"Jan", "Status":"NR"}, {"Month" : "Feb". "Status" :""}]
</code></pre>

<p>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:</p>

<pre><code>2015                                                
2014                                                
2015                                                
2014                                                
2015                                                
2014                                                
2015                                                
2014
</code></pre>

<p>This is the code:</p>

<pre><code>{% regroup x.LstPaymentBehaviour by Year as yearList %} 
  {% for ym in yearList  %}
    &lt;tr&gt;
           &lt;td&gt;&lt;strong&gt;{{ ym.grouper }}&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  {% endfor %}
</code></pre>

<p>What am I missing?</p>

<p>docs: <a href="https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#regroup" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#regroup</a></p>

<p><code>regroup</code> 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</p>

<pre><code>{% regroup x.LstPaymentBehaviour|dictsort:'Year' by Year as yearList %} 
</code></pre>

python django django-templates