Search code examples
pythondjangopython-2.6

How do I select distinct values in Django?


This is my code:

[app.system_name for app in App.objects.all().distinct('system_name')]

Gives me:

[u'blog', u'files', u'calendar', u'tasks', u'statuses', u'wiki', u'wiki', u'blog
', u'files', u'blog', u'ideas', u'calendar', u'wiki', u'wiki', u'statuses', u'ta
sks', u'survey', u'blog']

As you might expect I want all the unique values of the field system_name, but now I just get all App instances back.


Solution

    1. Specifying fields in distinct is only supported in Django 1.4+. If you're running 1.3, it's just ignoring it.

    2. If you are running Django 1.4, you must add an order_by clause that includes and starts with all the fields in distinct.

    3. Even then, specifying fields with distinct is only support on PostgreSQL. If you're running something else, such as MySQL, you're out of luck.

    All this information is in the docs.