在get_context_data

时间:2018-10-02 09:44:45

标签: python django

分页工作正常,直到我向QS添加reverse arg才能以反向模式对queryset进行排序。分页之后。 我可以使用get()函数并在那里分页,但是我认为对于这个问题应该是更好的解决方案。谢谢

model.py:

class Log(models.Model):
    user = models.ForeignKey('auth.User')
    comment = models.CharField()
    date_add = models.DateTimeField()
    class Meta:
        ordering = ['-date_add']

view.py:

class LogView(ListView):
    model = UserLog
    template_name = 'log.html'
    context_object_name = 'log_list'
    paginate_by = 13

    def get_queryset(self):
        return Log.objects.filter(user=self.request.user).all()

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(LogView, self).get_context_data(**kwargs)
        if 'reverse' in self.request.GET:
            context['log_list'] = Log.objects.filter(user=self.request.user).all().order_by('date_add')
        return context

2 个答案:

答案 0 :(得分:2)

将运行查询集的代码移动到get_queryset,以便在对查询集进行分页之前运行。

def get_queryset(self):
    queryset = Log.objects.filter(user=self.request.user).all()
    if 'reverse' in self.request.GET:
        queryset = queryset.order_by('date_add')
    return queryset

答案 1 :(得分:1)

get_context_data of the MultipleObjectMixin [GitHub]中调用分页:

def get_context_data(self, *, object_list=None, **kwargs):
    """Get the context for this view."""
    queryset = object_list if object_list is not None else self.object_list
    page_size = self.get_paginate_by(queryset)
    context_object_name = self.get_context_object_name(queryset)
    if page_size:
        paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
        context = {
            'paginator': paginator,
            'page_obj': page,
            'is_paginated': is_paginated,
            'object_list': queryset
        }
    else:
        context = {
            'paginator': None,
            'page_obj': None,
            'is_paginated': False,
            'object_list': queryset
        }
    if context_object_name is not None:
        context[context_object_name] = queryset
    context.update(kwargs)
    return super().get_context_data(**context)

通过覆盖字典的元素,您因此绕过此分页。

我认为在这种情况下最好将逻辑转移到get_queryset方法,在这种情况下,您甚至不必覆盖{{1} }:

get_context_data

请注意,上面有两个潜在问题:

  1. class LogView(ListView): model = UserLog template_name = 'log.html' context_object_name = 'log_list' paginate_by = 13 def get_queryset(self): if 'reverse' in self.request.GET: return Log.objects.filter(user=self.request.user).all().order_by('date_add') else: return Log.objects.filter(user=self.request.user).all()'reverse'不是 not 的情况下,您不对查询集进行排序,这意味着-除非您在模型中进行排序-否则就没有顺序,因此分页可能在多个页面上出现错误;
  2. 由于分页已经在self.request.GET中使用了page键,因此在更改GET参数的链接中可能会造成一些麻烦,因为如果您使用request.GET指定了url, ?page=3密钥将会丢失。