【问题标题】:Regrouping object list重新组合对象列表
【发布时间】:2018-02-09 20:47:11
【问题描述】:

我正在尝试按国家/地区对城市进行分组。

在我的模板中,以下工作 - 没有分组:

{% for item in object_list %}
{{ item.country}}
{{ item.city }}
{% endfor %}

但是,当我重新组合时:

{% regroup object_list by country as country_list %}
{% for item in country_list %}
{{ item.city }}
{% endfor %}

item.city 未呈现。

未分组的对象列表为:

<QuerySet [<Country: England>, <Country: France>, <Country: Germany>, <Country: Netherlands>]>

分组后:

Country: [GroupedResult(grouper=<Country: England>, list=[<City: Liverpool>, <City: London>, <City: Manchester>]), GroupedResult(grouper=<Country: Germany>, list=[<City: Munich>])....]

我做错了什么?

【问题讨论】:

    标签: django-templates


    【解决方案1】:

    来自文档:https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#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>
    

    注意循环语句中的.list 因此,对于您的代码块,您似乎应该使用

    {% regroup object_list by country as country_list %}
    {% for country in country_list %}
        {% for city in country.list %}
            <li>{{ city.name }}: {{ city.population }}</li>
        {% endfor %}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 2013-09-26
      • 1970-01-01
      • 2016-12-29
      • 2022-10-15
      • 1970-01-01
      • 2011-02-11
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      相关资源
      最近更新 更多