搜索结果没有出现在第二页中,我应该怎么解决才能解决问题?我正在使用Elasticsearch作为搜索引擎
index.html

     <ul>
                        {% for i in paginator.page_range %}
                              {% if i <= page_number|add:5 and i >= page_number|add:-5 %}

                                 <li class=" {% if i == page_number %} active {% endif %} " >
                                   <a href="?page={{forloop.counter}}">{{forloop.counter}}</a>
                                 </li>

                              {% endif %}

                        {% endfor %}
                          </ul>

这是在我的views.py

def index(request):
    q = request.GET.get('q')
    if q:
        articles = PostDocument.search().query("match", title=q, )
        paginator = Paginator(articles, 5)
        page_number = request.GET.get('page', 1)
        page_obj = paginator.get_page(page_number)

        return render(request, 'index.html', {
            'articles': page_obj.object_list,
            'paginator': paginator,
            'page_number': int(page_number),

        })

    else:
        articles = ''
        return render(request, 'index.html', {'articles': articles})


最佳答案

如果您编写?page=…,那么?q=…参数将被“丢弃”。诀窍是在转到下一个对象时将其添加到查询字符串中:

def index(request):
    q = request.GET.get('q')
    if q:
        articles = PostDocument.search().query("match", title=q, )
        paginator = Paginator(articles, 5)
        page_number = request.GET.get('page', 1)
        page_obj = paginator.get_page(page_number)

        return render(request, 'index.html', {
            'articles': page_obj.object_list,
            'paginator': paginator,
            'page_number': int(page_number),
            'q' : q
        })

    else:
        articles = ''
        return render(request, 'index.html', {'articles': articles})
然后用:
<a href="?page={{ forloop.counter }}&q={{ q|urlencode }}">{{forloop.counter}}</a>
|urlencode template filter [Django-doc]是对查询进行百分比编码所必需的,例如,如果它包含问号(?),&符(&)等。

10-07 19:14
查看更多