您的位置:首页 > 编程语言 > Go语言

在Django中使用DISTINCT

2016-07-12 10:41 387 查看
有时候想用distinct去掉queryset中的重复项,看django文章中是这么说的

>>> Author.objects.distinct()
[...]

>>> Entry.objects.order_by('pub_date').distinct('pub_date')
[...]

>>> Entry.objects.order_by('blog').distinct('blog')
[...]

>>> Entry.objects.order_by('author', 'pub_date').distinct('author', 'pub_date')
[...]

>>> Entry.objects.order_by('blog__name', 'mod_date').distinct('blog__name', 'mod_date')
[...]

>>> Entry.objects.order_by('author', 'pub_date').distinct('author')
[...]
Note


django文档中特别介绍了,distinct的列一定要先order_by并且在第一项。

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.

完全照做,用的mysql数据库最后出现了这样的警告:

 raise NotImplementedError('DISTINCT ON fields is not supported by this database backend')

NotImplementedError: DISTINCT ON fields is not supported by this database backend

告诉我数据库不支持。

当然可以这样:

items = []
for item in query_set:
if item not in items:
items.append(item)


如果想用distinct的话,在distinct前面加上values或values_list

 u.comment_set.values("forum").distinct()

[{'forum': 1L}, {'forum': 2L}]

u.comment_set.values_list("forum", flat=True).distinct()

[1L, 2L]

其实就相当于values_list获得了一个数组然后set()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: