distinct values in list

938 views
Skip to first unread message

nixon66

unread,
Feb 20, 2009, 7:46:36 PM2/20/09
to Django users
I'm using this in a template to get a list of items in the list.

<ul>
{% for item in list %}
<li>{{ item.var }}</li>
{% endfor %}
</ul>

The problem is that I get duplicate values when I do this. So if var1
appears in my database more than once, I get it as many times as it
appears. I looked at using the distinct() function but could not quite
figure out how to get it to work the way I want. Any suggestions?
Thanks in advance.

Alex Gaynor

unread,
Feb 20, 2009, 7:49:08 PM2/20/09
to django...@googlegroups.com
If you only want to print one value from the items you can do something like:

Model.objects.values_list('field', flat=True).distinct()

that will return a list of all the values in that field, but distint of course.

Alex

--
"I disapprove of what you say, but I will defend to the death your right to say it." --Voltaire
"The people's good is the highest law."--Cicero

nixon66

unread,
Feb 20, 2009, 7:58:15 PM2/20/09
to Django users
tried

Place.objects.values_list('county', flat=true).distinct()

Now its not returning any values.

On Feb 20, 7:49 pm, Alex Gaynor <alex.gay...@gmail.com> wrote:

Alex Gaynor

unread,
Feb 20, 2009, 7:59:49 PM2/20/09
to django...@googlegroups.com
It doesn't return models anymore, it just returns the individual items so isntead of

{% for item in lst  %}
   {{ item.var }}
{% endfor %}

you would do

{% for item in lst %}
   {{ item }}
{% endfor %}

nixon66

unread,
Feb 20, 2009, 8:05:00 PM2/20/09
to Django users
Alex,

Once again sir you have shown me the light. Thank you.

On Feb 20, 7:59 pm, Alex Gaynor <alex.gay...@gmail.com> wrote:
Reply all
Reply to author
Forward
0 new messages