django —— Queryset 切片后过滤(filter)和排序(order_by)错误

django —— Queryset 切片后过滤和排序错误

  • AssertionError: Cannot reorder a query once a slice has been taken.
    • 问题描述
    • 解决方法
  • AssertionError: Cannot filter a query once a slice has been taken.
    • 问题描述
    • 解决方法

AssertionError: Cannot reorder a query once a slice has been taken.

问题描述

# 目的:取 Article 表中前十数据并将获取到的十条数据根据 pub_date 排序
queryset = Article.objects.all()[:10].order_by("pub_date")

# 报错:
   1069         """Return a new QuerySet instance with the ordering changed."""
   1070         assert self.query.can_filter(), \
-> 1071             "Cannot reorder a query once a slice has been taken."
   1072         obj = self._chain()
   1073         obj.query.clear_ordering(force_empty=False)

AssertionError: Cannot reorder a query once a slice has been taken.

解决方法

# 1. 先切片获取前十条数据
queryset = Article.objects.all()[:10]
# 2. 根据 pub_date 进行排序
queryset = sorted(queryset, key=lambda item: item.pub_date)

AssertionError: Cannot filter a query once a slice has been taken.

问题描述

# 目的:取 Article 表中前十数据并从获取到的十条数据里过滤出 pub_date=2020-07 的数据
queryset = Article.objects.all()[:10].filter(pub_date="2020-07")

# 报错:
    902         if args or kwargs:
    903             assert self.query.can_filter(), \
--> 904                 "Cannot filter a query once a slice has been taken."
    905 
    906         clone = self._chain()

AssertionError: Cannot filter a query once a slice has been taken.

解决方法

# 1. 先切片获取前十条数据
queryset = Article.objects.all()[:10]
# 2. 通过列表生成器获取
queryset = [item for item in queryset if item.pub_date == "2020-07"]

你可能感兴趣的:(Djnago,错误集锦,django,filter)