在Django中使用DISTINCT

在尝试使用Django的DISTINCT去除QuerySet重复项时,如果按照指定字段进行操作,可能会遇到数据库不支持DISTINCT ON fields的错误。为了解决这个问题,可以改用`values`或`values_list`方法前缀,如`u.comment_set.values("forum").distinct()`和`u.comment_set.values_list("forum", flat=True).distinct()`,这两种方式可以在MySQL数据库中有效去除重复值。" 123521020,12894021,PHP CSV导出到Excel乱码问题解决方案,"['PHP', '开发语言', 'CSV处理']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值