前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在Django中使用DISTINCT

在Django中使用DISTINCT

作者头像
KEVINGUO_CN
发布2020-03-16 10:14:23
1.4K0
发布2020-03-16 10:14:23
举报
文章被收录于专栏:全栈全栈

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-02-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档