Select distinct in Django

2019-05-21 04:22发布

问题:

What am I doing wrong here?

[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.

回答1:

  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.



回答2:

You have to order by the same field name when using distinct with a field name:

App.objects.order_by('system_name').distinct('system_name')

From the doc:

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.

For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don't specify an order, you'll get some arbitrary row.



回答3:

You can use values_list() when using distinct().

App.objects.values_list('system_name').distinct()