在Django中使用DISTINCT
2016-07-12 10:41
387 查看
有时候想用distinct去掉queryset中的重复项,看django文章中是这么说的
django文档中特别介绍了,distinct的列一定要先order_by并且在第一项。
When you specify field names, you must provide an
and the fields in
in the same order.
For example,
you the first row for each value in column
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
告诉我数据库不支持。
当然可以这样:
如果想用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()
>>> 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()
相关文章推荐
- django工作原理
- Google的高级搜索
- Django模板系统
- golang之cgo一---go与C基本类型转换
- 2天值75亿美元?AR手游Pokemon Go全球爆红背后的5大原因
- 优化 Go 中的 map 并发存取
- 5个GoLang 应用优化措施
- Go性能优化技巧1/10
- Go性能优化技巧2/10
- Go 性能优化技巧 3/10
- Go 性能优化技巧 4/10
- Go 性能优化技巧 5/10
- Go 性能优化技巧 6/10
- Go 性能优化技巧 7/10
- Go 性能优化技巧 8/10
- HDU5546 Ancient Go DFS
- goldengate 学习有用网址
- GO的GDB调试
- 统一日志管理-Mongo 篇
- 大话设计模式(Golang) 二、策略模式