Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 339
arno_v Avatar asked Nov 30 '22 03:11

arno_v


1 Answers

  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.

like image 166
Chris Pratt Avatar answered Dec 06 '22 22:12

Chris Pratt