Django 分页 returns 整个数据库第 2 页

Django Pagination returns entire database on page 2

正在尝试让分页在 Django 中发挥作用。在第 1 页上看起来不错,但是当我转到第 2 页时,我可以看到显示了我的整个数据库。

这是我的代码:

class AdvancedSearch(ListView):
        template_name= 'saferdb/AdvancedQuery.html'

        def get(self, request):
            c = request.GET.getlist('opeclass')
            q = Question.objects.all()

            #Ugly q filtering methods

            paginator = Paginator(q, 25)
            page = request.GET.get('page')
            contacts = paginator.get_page(page)
            return render(request, 'saferdb/list.html', {'text' : count , 'contacts': contacts})

URLS.py

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^query/$', views.QueryView.as_view(), name='query'),
    url(r'^advanced/$', views.AdvancedSearch.as_view(), name='advanced'),
]

模板代码:

<form method="get">

<!--- bunch of selection to filer output by --->
<div class="pagination">
    <span class="step-links">
        {% if contacts.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ contacts.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
        </span>

        {% if contacts.has_next %}
            <a href="?page={{ contacts.next_page_number }}">next</a>
            <a href="?page={{ contacts.paginator.num_pages }}">last &raquo;</a>
        {% endif %}
    </span>
</div>

如果您使用 def get 方法,则不应使用 ListView,而应使用 TemplateView 或 View。 ListView 有 paginate_by 属性,例如

class AdvancedSearch(ListView):
    template_name= 'saferdb/AdvancedQuery.html'
    paginate_by=25
    page_kwarg = 'page'

page_kwarg == 'page' 默认情况下它会检查你的 url 并获取 page_kwarg 值的数据,所以你可以用 ListView 做的是这个

class AdvancedSearch(ListView):
    template_name= 'saferdb/AdvancedQuery.html'
    paginate_by=25
    context_object_name = 'contacts'
    model = Question

    def get_queryset(self):
        c = self.request.GET.getlist('opeclass')
        q = Question.objects.all()
        ...
        return queryset

    def get_context_data(self, **kwargs):
        context = super(AdvancedSearch, self).get_context_data(**kwargs)
        context.update({...})
        return context             

实际上是这样

P.S。在我看来,这有点奇怪,您按问题模型查询集分页,但在响应查询集中称为联系人。您的代码中可能遗漏了什么重要的东西?