Reputation: 5863
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
Upvotes: 7
Views: 12387
Reputation: 981
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.
Upvotes: 14
Reputation:
It is usually best to change your Query first to ensure you get the least amount of data. In this case, you could edit your query as follows:
cities_with_uniq_friend_names = City.objects.all().distinct('friend_name')
Now when you iterate over cities_with_uniq_friend_names
it will give you unique friend names
Upvotes: 4