views:

119

answers:

2

Assume I have a such model:

class Foo(models.Model):
    name = models.CharField("ad",max_length=25)
    type = models.ForeignKey(Type)

So at the database I have Foo objects with same name field but different types ie:

name type
A     1
A     2
B     1
C     2
A     3
B     3

I will use this information inorder to generate a html select form, displaying all possible (distinct) names so in the end my select form will be showing such:

<select>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>

How do I get a list of distinct values for name?

+2  A: 
Foo.objects.values('name').distinct().order_by('name')
Till Backhaus
this seem to work thanks but the output is such:{'name': u'A}{'name': u'B}{'name': u'C}how can I fix this problem ?
Hellnar
for the record I have it such: names = [i["name"] for i in Foo.objects.values('name').distinct().order_by('name')]
Hellnar
See my answer for an easier way to do this.
Daniel Roseman
+6  A: 

In answer to your subsequent question to Till, an easier way is:

Foo.objects.values_list('name', flat=True).distinct().order_by('name')
Daniel Roseman