Python Team
Python Team

Reputation: 1171

How to avoid duplicate values while retrieving from database in django

I need to avoid duplicate values while retrieving from database in django. I am having the result dictionary as list.

 queryset = [{'name':'shankar','Age':'24'},{'name':'Manoj','Age':'26'},   {'name':'shankar','Age':'25'}]

I need to display the value in dropdown list as the value shankar and Manoj. I am retrieving the value like the query below

 queryset = Books.objects.all()

Now i want to avoid the duplicate value while displaying dropdown list in template page.

Thanks in advance.

Upvotes: 1

Views: 2613

Answers (2)

Panta
Panta

Reputation: 199

Use values() instead all() method in queryset:

queryset = Book.objects.values('name').distinct()

And in your template:

<select>
{% for obj in object_list %}
<option>{{ obj.name }}</option>
{% endfor %}
</select>

Upvotes: 0

Pynchia
Pynchia

Reputation: 11590

use

queryset = Books.objects.all().distinct('name')

See docs here:

"..On PostgreSQL only, you can pass positional arguments (*fields) in order to specify the names of fields to which the DISTINCT should apply. This translates to a SELECT DISTINCT ON SQL query. Here’s the difference. For a normal distinct() call, the database compares each field in each row when determining which rows are distinct. For a distinct() call with specified field names, the database will only compare the specified field names."

Upvotes: 1

Related Questions