码迷,mamicode.com
首页 > Windows程序 > 详细

090:QuerySet API详解-distinct

时间:2019-01-17 23:40:02      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:分享图片   字段   nbsp   str   代码   filter   因此   技术   数据库   

QuerySet API详解-distinct:

distinct :去除掉那些重复的数据。这个方法如果底层数据库用的是 MySQL ,那么不能传递任何的参数。比如想要提取所有销售的价格超过80元的图书,并且删掉那些重复的,那么可以使用 distinct 来帮我们实现,示例代码如下:

books = Book.objects.filter(bookorder__price__gte=80).distinct()

需要注意的是,如果在 distinct 之前使用了 order_by ,那么因为 order_by 会提取 order_by 中指定的字段,因此再使用 distinct 就会根据多个字段来进行唯一化,所以就不会把那些重复的数据删掉。示例代码如下:

 

orders = BookOrder.objects.order_by("create_time").values("book_id").distinct()
# 或如下代码:
books = Book.objects.annotate(book_price=F("bookorder__price")).filter(bookorder__price__gte=80).distinct()

那么以上代码因为使用了 order_by ,即使使用了 distinct ,也会把重复的 book_id 提取出来。

实例代码截图如下:

技术分享图片

 

090:QuerySet API详解-distinct

标签:分享图片   字段   nbsp   str   代码   filter   因此   技术   数据库   

原文地址:https://www.cnblogs.com/zheng-weimin/p/10284874.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!