views:

76

answers:

1

I'm struggling getting my head around the Django's ORM. What I want to do is get a list of distinct values within a field on my table .... the equivalent of one of the following:

SELECT DISTINCT myfieldname FROM mytable

(or alternatively)

SELECT myfieldname FROM mytable GROUP BY myfieldname

I'd at least like to do it the Django way before resorting to raw sql. For example, with a table:

id, street, city

1, Main Street, Hull

2, Other Street, Hull

3, Bibble Way, Leicester

4, Another Way, Leicester

5, High Street, Londidium

I'd like to get: Hull, Leicester, Londidium.

+1  A: 

say your model is 'Shop'

class Shop(models.Model):
    street = models.CharField(max_length=150)
    city = models.CharField(max_length=150)

To query your DB, you just have to call :

models.Shop.objects.values('city').distinct()  # returns a dictionnary for results

or

models.Shop.objects.values_list('city').distinct()  # returns a list for results

you can also add flat=True to values_list to have a flat list.

my 2 cents.

jujule
Actually that works. However! I couldn't get it to work on all my models. Weidly, it worked on some but not others. For those that have a Meta ordering it doesn't work. So, you have to clear the ordering on the queryset first.models.Shop.objects.order_by().values('city').distinct()
alj