我正试图按国家分组城市。
在我的模板中,以下工作 - 没有分组:
{% 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>])....]
我做错了什么?
答案 0 :(得分:0)
从文档中: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 %}