Select distinct in Django

孤街浪徒 提交于 2019-12-08 01:30:14

问题


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()


来源:https://stackoverflow.com/questions/9518947/select-distinct-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!