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