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的妙用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值