在 Django 模板中使用重组

Tah*_*bal 2 python django django-templates

我收到一个 JSON 对象,其中包含许多对象和对象列表等。在这些列表之一中是这样的 Year 列表:

[{'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'}] 
Run Code Online (Sandbox Code Playgroud)

我需要按年份对这个列表进行分组,并根据年份显示月份。例如:

{"2015":[{"Month":"Jan", "Status":"NR"}, {"Month" : "Feb". "Status" :""}]
Run Code Online (Sandbox Code Playgroud)

现在,我使用的代码没有按照我想要的方式工作,而是根据月数重复年份:

2015                                                
2014                                                
2015                                                
2014                                                
2015                                                
2014                                                
2015                                                
2014
Run Code Online (Sandbox Code Playgroud)

这是代码:

{% regroup x.LstPaymentBehaviour by Year as yearList %} 
  {% for ym in yearList  %}
    <tr>
           <td><strong>{{ ym.grouper }}</strong></td>
    </tr>
  {% endfor %}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

小智 6

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

regroup首先期望有序数据。如果相同年份的所有项目都是连续的,那么您将获得所需的输出。所以首先对你的输入数据进行排序

{% regroup x.LstPaymentBehaviour|dictsort:'Year' by Year as yearList %} 
Run Code Online (Sandbox Code Playgroud)