Python 如何在Django循环模板中对订购的项目进行分组(打印标题)?

Python 如何在Django循环模板中对订购的项目进行分组(打印标题)?,python,django,django-templates,Python,Django,Django Templates,我有一个Django模型,看起来像这样: class City(models.Model): country = models.CharField(max_length=50) city = models.CharField(max_length=50) population = models.IntegerField() {% regroup city_list|dictsort:"country" by country as country_list %} <

我有一个Django模型,看起来像这样:

class City(models.Model):
    country = models.CharField(max_length=50)
    city = models.CharField(max_length=50)
    population = models.IntegerField()
{% regroup city_list|dictsort:"country" by country as country_list %}

<ul>
{% for country in country_list %}
    <li><strong>{{ country.grouper }}</strong>
        <ul>
            {% for item in country.list %}
                <li>{{ item.city }}</li>
            {% endfor %}
        </ul>
    </li>
{% endfor %}
</ul>
我想在模板中打印按国家分组的城市列表,如下所示:

Canada Calgary Montreal Toronto Mexico Juarez United States Atlanta Chicago Denver 加拿大 卡尔加里 蒙特利尔 多伦多 墨西哥 华雷斯 美国 亚特兰大 芝加哥 丹佛 我可以很容易地按国家名称订购,但我只想在for循环中第一次看到模型的国家名称时将其打印为标题。在Django有没有一种明智的方法可以做到这一点

在视图或查询中,我是否可以为模板提供一个布尔值作为“首次出现”,或者在模板中提供一个聪明的方法?

请参见,您可以这样做:

class City(models.Model):
    country = models.CharField(max_length=50)
    city = models.CharField(max_length=50)
    population = models.IntegerField()
{% regroup city_list|dictsort:"country" by country as country_list %}

<ul>
{% for country in country_list %}
    <li><strong>{{ country.grouper }}</strong>
        <ul>
            {% for item in country.list %}
                <li>{{ item.city }}</li>
            {% endfor %}
        </ul>
    </li>
{% endfor %}
</ul>
{%regroup city_list}按国家排序:“country”为country_list%}
    {国家/地区中的国家/地区的%u列表%}
  • {{country.grouper}}
      {country.list%中的项目为%1}
    • {{item.city}
    • {%endfor%}
  • {%endfor%}
看,您可以这样做:

class City(models.Model):
    country = models.CharField(max_length=50)
    city = models.CharField(max_length=50)
    population = models.IntegerField()
{% regroup city_list|dictsort:"country" by country as country_list %}

<ul>
{% for country in country_list %}
    <li><strong>{{ country.grouper }}</strong>
        <ul>
            {% for item in country.list %}
                <li>{{ item.city }}</li>
            {% endfor %}
        </ul>
    </li>
{% endfor %}
</ul>
{%regroup city_list}按国家排序:“country”为country_list%}
    {国家/地区中的国家/地区的%u列表%}
  • {{country.grouper}}
      {country.list%中的项目为%1}
    • {{item.city}
    • {%endfor%}
  • {%endfor%}

纯粹的天才你是纯粹的天才你是