1

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.

2
  • 1
    They aren't really "duplicate" because of the age discrepancy...How do you want to choose between the two? Commented May 14, 2015 at 7:29
  • So then i need to avoid display "name" value more times. is there anyother way to do it. am jus searching anyotherway to avoid while display in built-in template tags Commented May 14, 2015 at 7:54

2 Answers 2

1

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."

Sign up to request clarification or add additional context in comments.

5 Comments

no need to pass it as a keyword argument, just pass the name of each field. See my answer and the docs for an example. By the way, are you using PostgreSQL?
yes.. when i pass "name" field in distinct function, it shouldn't get the name value from database.
distinct is used to filter the records. In the returned queryset, the objects have all the fields (name and Age), as normal.
Please let me know if my answer solves your question (accept it or indicate why not)
when i use distinct keyword, it shouldn't get the value of "name". I need to get the value one time. it shows the output like "[{'name':u' ','Age':'24'},{'name':u' ','Age':'26'},{'name':u' ','Age':'25'}]" . Anyother idea??
0

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>

1 Comment

I have done it with the help of values_list('name').distinct(). But it shows the error while displaying. it shows Attribute Error: 'unicode object has no attribute pk'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.