gamer
gamer

Reputation: 5863

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

Upvotes: 7

Views: 12387

Answers (3)

L.Grillo
L.Grillo

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

user142650
user142650

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

sgp
sgp

Reputation: 1768

Why do you want to do it in the template? Try to modify cities itself so that it has unique entries. You could convert your list to a set and then re-convert it back:

cities_unique = list(set(cities))

If you have to show unique attributes, use the regroup feature

Upvotes: 3

Related Questions