在Django中使用DISTINCT

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lanix516/article/details/51888082

有时候想用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)

扫描二维码关注公众号,回复: 5675381 查看本文章

如果想用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]

猜你喜欢

转载自blog.csdn.net/lanix516/article/details/51888082