【问题标题】:I wanna paginate in class view, but an error happened "Cannot filter a query once a slice has been taken."我想在类视图中分页,但发生错误“一旦切片已被获取,就无法过滤查询”。
【发布时间】:2021-06-23 05:17:43
【问题描述】:

我想在 Django 的 ListView 中实现分页。我可以在函数视图中重写视图,但我想知道如何在类视图中进行分页练习。

我想在这里做的是获取登录用户过滤的数据,并以 20 分页显示它们(数字无关紧要)。例如,如果 Alex 当前正在登录,我想显示 Alex 的数据库中以 20 为分页的数据。

但是,当我编写下面的代码时,我收到一个错误“一旦获取切片,就无法过滤查询”。所以,现在在 HTML 文件上,有所有用户的数据,比如 Alex 的数据、Bob 的数据、Lisa 的数据,以及所有其他用户的数据。

我尝试将paginate_by = 20 放在 get_context_data 函数下,但不起作用。我什至认为我可能不会将 paginate_by 与 get_context_data 一起使用。

class FoodList(LoginRequiredMixin, ListView):
  model = Food
  template_name = 'base/all_foods.html'
  context_object_name = 'foods'
  ordering = ['-created']
  paginate_by = 20
  def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['color'] = 'red'
    context['foods'] = context['foods'].filter(user=self.request.user)

如果我需要提供更多信息,请告诉我。 任何建议都是有帮助的,并提前感谢您的帮助!

【问题讨论】:

    标签: python python-3.x django django-views


    【解决方案1】:

    是因为context['foods'] = context['foods'].filter(user=self.request.user)这一行。

    您的context_object_name = 'foods'。在paginationget_context_data 方法中对其进行切片后,您将对其进行过滤。

    如果你想过滤你的queryset 并且仍然有pagination,你可以这样做:

    class FoodList(LoginRequiredMixin, ListView):
        model = Food
        template_name = 'base/all_foods.html'
        context_object_name = 'foods'
        ordering = ['-created']
        paginate_by = 20
    
        def get_queryset(self):
            queryset = super().get_queryset().filter(user=self.request.user)
            return queryset
    
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context['color'] = 'red' 
            return context 
    

    现在它可以正常工作了。

    P.S. 始终在 get_queryset 方法或 queryset 属性中过滤或更改您的查询集。不要在get_context_data 方法中这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 2021-03-05
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      相关资源
      最近更新 更多