views:

117

answers:

1

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?

+2  A: 

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.

celopes
This seems to be working. Do you know of a way of checking the query that's being generated by a django expression?
Ezequiel
Ok... It's been asked already http://stackoverflow.com/questions/1074212/show-the-sql-django-is-running
Ezequiel
Great.. I checked and you are 100% correct. Thank youFoo.objects.all().values_list('item', flat=True).distinct()I'm starting to love Django as much as I love Python
Ezequiel
You don't need the `.all()` in there. Just `Foo.objects.values_list('item', flat=True)`
celopes
to see the sql: just append `.query.as_sql()` to any queryset
lawrence