django学习——通过regroup方法对对象进行分组
regroup
用相似对象间共有的属性重组列表。
比如有以下城市列表,我们想要按照国家名称对其进行分类:
cities = [{'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},{'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},{'name': 'New York', 'population': '20,000,000', 'country': 'USA'},{'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},{'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]
得到类似如下的结果:
印度
孟买:19,000,000
加尔各答:15,000,000
美国
纽约:20,000,000
芝加哥:7,000,000
日本
东京:33,000,000
你可以使用{% regroup %}标签来给每个国家的城市分组。 以下模板代码片段将实现这一点:
{% regroup cities by country as country_list %}<ul>
{% for country in country_list %}<li>{{ country.grouper }}<ul>{% for city in country.list %}<li>{{ city.name }}: {{ city.population }}li>{% endfor %}ul>li>
{% endfor %}
ul>
让我们来看看这个例子。 {% regroup %}有三个参数: 你想要重组的列表, 被分组的属性, 还有结果列表的名字. 在这里,我们通过country_list属性重新分组country列表,并调用结果cities。
{% regroup %}产生一个清单(在本例中为country_list的组对象。 组对象是具有两个字段的namedtuple()的实例:
- grouper - 按分组的项目(例如,字符串“India”或“Japan”)。
- list - 此群组中所有项目的列表(例如,所有城市的列表,其中country =’India’)。
在Django更改1.11:
组对象已从字典更改为namedtuple()。
Because {% regroup %} produces namedtuple() objects, you can also write the previous example as:
{% regroup cities by country as country_list %}<ul>
{% for country, local_cities in country_list %}<li>{{ country }}<ul>{% for city in local_cities %}<li>{{ city.name }}: {{ city.population }}li>{% endfor %}ul>li>
{% endfor %}
ul>
这个问题的最简单的解决方案是确保在你的视图代码中,数据是根据你想要显示的顺序排序。
另一个解决方案是使用dictsort过滤器对模板中的数据进行排序,如果您的数据在字典列表中:
{% regroup cities|dictsort:"country" by country as country_list %}
分组其他属性
一个有效的模版查找是一个regroup标签的合法的分组属性。包括方法,属性,字典健和列表项。 例如,如果“country”字段是具有属性“description”的类的外键,则可以使用:
{% regroup cities by country.description as country_list %}
或者,如果choices是具有choices的字段,则它将具有作为属性的get_FOO_display()方法,显示字符串而不是country键:
{% regroup cities by get_country_display as country_list %}
{{ country.grouper }}现在会显示choices。
参考文档:官方文档 ,Django模板标签regroup的妙用
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
