Django重组不按预期工作

9 django

我最近跳进了学习django.

我正在使用citylist渲染我的模板,

{'citylist': Cities.objects.all()}
Run Code Online (Sandbox Code Playgroud)

并希望在模板中的国家/地区重新组合(与django-docs相同):

{% regroup citylist by country as coutrylist %}

<ul>
{% for country in countrylist %}
    <li>{{ country.grouper }}
    <ul>
        {% for c in country.list %}
        <li>{{ c.name }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)

但我得到一些意想不到的结果,

France
  Strasbourg

Australia
  Penrith
  Sydney

US
  Larsen Bay

France
  Reims

US
  Avenal
Run Code Online (Sandbox Code Playgroud)

我不认为我在模板中做错了什么.还是它的一个bug?

sim*_*rsh 9

问题不在代码中,而是在您注入的数据中.

将您的上下文更改为

{'citylist': Cities.objects.all().order_by('country')}
Run Code Online (Sandbox Code Playgroud)

django-docs提到了这一点

这个问题的最简单的解决方案是在您的视图代码中确保根据您想要显示的方式对数据进行排序.

  • 你的答案是正确的,并不能使你的态度出错. (13认同)