Question

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?

Was it helpful?

Solution

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

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

OTHER TIPS

Foo.objects.values('name').distinct().order_by('name')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top