I’m a Django newbie and I wonder if there is a more efficient way (at a database level) of doing the following.
I have the model:
class Foo(models.Model):
item=models.IntegerField()
another_item=models.IntegerField()
And want to get an iterable of all the distinct values of “item”.
This is what I have so far:
distinct=set([row.item for row in Foo.objects.all()])
This is easy to understand. But if I’m understanding how Django works then the SQL query is not very efficient because it is something like:
SELECT * FROM DB
when I only need:
SELECT DISTINCT item FROM DB
Any way of doing this more efficiently?
You want to use the
distinctclause in combination with thevaluesorvalues_listclauses.Doc starts here.
distinct,valuesandvalues_listare all in there.So you could do:
And that would return a list of item – matching your
SELECT DISTINCT item FROM DBquery.