django, a good way of querying a distinct model
Assume I have a such model:
class Foo(models.Model):
name = models.CharField("ad",max_length=25)
type = models.ForeignKey(开发者_StackOverflowType)
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
?
In answer to your subsequent question to Till, an easier way is:
Foo.objects.values_list('name', flat=True).distinct().order_by('name')
Foo.objects.values('name').distinct().order_by('name')
精彩评论