如何在Django中选择不同的值? [英] How do I select distinct values in Django?
问题描述
这是我的代码:
[app.system_name for app in App.objects.all().distinct('system_name')]
给我:
[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']
您可能希望我想要system_name字段的所有唯一值,但是现在我只获取了所有App实例.
As you might expect I want all the unique values of the field system_name, but now I just get all App instances back.
推荐答案
-
仅在Django 1.4及更高版本中支持在
distinct
中指定字段.如果您运行的是1.3,那就只是忽略它.
Specifying fields in
distinct
is only supported in Django 1.4+. If you're running 1.3, it's just ignoring it.
如果正在运行Django 1.4,则必须添加一个 order_by
子句,该子句包括并以 distinct
中的所有字段开头.
If you are running Django 1.4, you must add an order_by
clause that includes and starts with all the fields in distinct
.
即使这样,也仅在PostgreSQL上支持使用 distinct
指定字段.如果您正在运行其他内容(例如MySQL),则说明您不走运.
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.
所有这些信息都在 查看全文