Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django template show only distinct value

Suppose I have a query:

cities = City.objects.all()

In my template I have done:

{% for city in cities %}
    {{city.friend_name}}
    <a href="{% url "my_url" city.friend_name.id %}" class="btn btn-primary">View Detail</a>
{% endfor %}

It gives me name of 4 friends with id say alex 1, matt 2, mack 3, mack 3. But here mack is repeated. I only want mack once. If the values are repeated I want it to be printed only once.

How can I do this in template. I mean is there something like {{city.friend_name|distinct}} or something else

I dont want unique city. I want friends name on city to be unique.

Thank you

like image 281
gamer Avatar asked Dec 01 '22 14:12

gamer


1 Answers

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 %}

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

like image 151
L.Grillo Avatar answered Dec 06 '22 08:12

L.Grillo