django Dajngo:使用基于类的视图在搜索结果中分页

tzcvj98z  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(135)

我想按我在表单中输入的关键字分页。
我使用下面的类

def pageNotFound(request, exceprion):
    return HttpResponseNotFound("<h2>Page not found</h2>")

def get_quotes():

    top_tags = get_top_tags()

    context = {
        "top_tags": top_tags,
        "functional_menu": functional_menu,
    }

    return context

class Main(ListView):
    model = Quote
    paginate_by = 10
    template_name = "quotes/index.html"
    context_object_name = "quotes"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update(get_quotes())
        return context

class SearchedResults(ListView):
    model = Quote
    paginate_by = 10
    template_name = "quotes/index.html"
    context_object_name = "quotes"

    def get_queryset(self):
        query = self.request.GET.get("search_query")
        if query:
            queryset = Quote.objects.filter(
                Q(quote__icontains=query)
                | Q(tags__name__icontains=query)
                | Q(author__fullname__icontains=query)
            ).distinct()
        else:
            queryset = super().get_queryset()
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

问题是,当您转到下一页时,表单字段被清除,查询的值为None query=None。整个分页变为未定义。分页跨页时如何保存查询集?

u4vypkhs

u4vypkhs1#

这与视图没有太大关系,而是与分页的链接有关。你可以在视图中创建一个helper函数:

class SearchedResults(ListView):
    model = Quote
    paginate_by = 10
    template_name = 'quotes/index.html'
    context_object_name = 'quotes'

    def urlencode_search(self):
        qd = self.request.GET.copy()
        qd.pop(self.page_kwarg, None)
        return qd.urlencode()

    def get_queryset(self):
        query = self.request.GET.get('search_query')
        queryset = super().get_queryset(*args, **kwargs)
        if query:
            queryset = queryset.filter(
                Q(quote__icontains=query)
                | Q(tags__name__icontains=query)
                | Q(author__fullname__icontains=query)
            ).distinct()
        return queryset

在模板中,然后使用以下命令链接到其他页面:

<a href="?page={{ page_obj.next_page_number }}&amp;{{ view.urlencode_search }}">next page</a>

这是指向某个页面的所有链接。

相关问题