090:QuerySet API详解-distinct

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 提取出来。

实例代码截图如下:

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