django 模板只显示不同的值

gam*_*mer 4 python django templates

假设我有一个查询:

cities = City.objects.all()
Run Code Online (Sandbox Code Playgroud)

在我的模板中,我做了:

{% for city in cities %}
    {{city.friend_name}}
    <a href="{% url "my_url" city.friend_name.id %}" class="btn btn-primary">View Detail</a>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

它给了我 4 个朋友的名字,id 说 alex 1、matt 2、mack 3、mack 3。但这里重复了 mack。我只想要马克一次。如果值重复,我希望它只打印一次。

我怎样才能在模板中做到这一点。我的意思是有类似的东西{{city.friend_name|distinct}}或其他东西

我不想要独特的城市。我希望城市上的朋友名字是独一无二的。

谢谢

L.G*_*llo 11

Don't use extra input parameters, just use the "ifchanged" django builtin filter: https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#ifchanged

{% for city in cities|dictsort:'friend_name' %}
    {% ifchanged %}{{city.friend_name}}{% endifchanged %}    
    <a href="{% url "my_url" city.friend_name.id %}" class="btn btn-primary">View Detail</a>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

p.s. i know it's 3 years old but it's an helpful answer for someone else.


sgp*_*sgp 3

为什么要在模板中做呢?尝试修改cities自身以使其具有唯一的条目。您可以将您的转换list为 a set,然后将其重新转换回来:

cities_unique = list(set(cities))

如果您必须显示独特的属性,请使用重组功能