2

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?

Ezequiel
  • 668
  • 2
  • 9
  • 25

1 Answers1

4

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.

cethegeek
  • 6,286
  • 35
  • 42
  • This seems to be working. Do you know of a way of checking the query that's being generated by a django expression? – Ezequiel Feb 02 '10 at 01:49
  • Ok... It's been asked already http://stackoverflow.com/questions/1074212/show-the-sql-django-is-running – Ezequiel Feb 02 '10 at 01:52
  • Great.. I checked and you are 100% correct. Thank you Foo.objects.all().values_list('item', flat=True).distinct() I'm starting to love Django as much as I love Python – Ezequiel Feb 02 '10 at 01:55
  • You don't need the `.all()` in there. Just `Foo.objects.values_list('item', flat=True)` – cethegeek Feb 02 '10 at 02:54
  • to see the sql: just append `.query.as_sql()` to any queryset – Lawrence Feb 03 '10 at 09:47