Reputation: 718
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?
Upvotes: 2
Views: 2662
Reputation: 6394
You want to use the distinct
clause in combination with the values
or values_list
clauses.
Doc starts here. distinct
, values
and values_list
are all in there.
So you could do:
Foo.objects.values_list('item', flat=True)
And that would return a list of item - matching your SELECT DISTINCT item FROM DB
query.
Upvotes: 4