django与多个列表分页

时间:2018-05-07 15:19:57

标签: python django django-templates django-endless-pagination

我正在使用Django分页。有2个场景

  1. 当用户登陆此页面时,结果集会返回预先过滤的结果,因此我不一定需要对结果进行分页。
  2. 当用户关闭过滤器时,我需要显示所有结果(这是我需要分页时,10000条记录)这些记录以不同列表的形式显示 我将结果作为压缩格式发送。
  3. 我无法通过多个列表/结果集进行分页。

1 个答案:

答案 0 :(得分:0)

您只需要为Paginator提供一个对象列表 您希望在每个页面上显示的项目数量,并为您提供访问每个页面的项目的方法:Django Doc

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

# 1st OPTION: in case you have multiple queryset 
from itertools import chain
queryset1 = Queryset.objects.all()
queryset2 = Queryset.objects.all()
YourObjectList = sorted(chain(queryset1,queryset2),reversed=True)
# 2nd Option: with Django union queryset
YourObjectList = queryset1.union(queryset2)

object_list = YourObjectList # Queryset of List of Objects
number_items = 10  # The number of items you’d like to have on each page

page = request.GET.get("page",1)
# Get the page parameter i.e localhost:8080?page=1
paginator = Paginator(object_list,number_items)
try:
    object_list = paginator.page(page)
except PageNotAnInteger:
    object_list = paginator.page(1)
except EmptyPage:
    object_list = paginator.page(paginator.num_pages)

# add the [object_list] to context for [template]

在模板中,您可以遍历它以显示所有对象

{% for obj in object_list %}
    {{obj}}<br>
{% endfor %}

BONUS :如何显示Paginator几乎像this one

{% if object_list.has_other_pages %}
    <div class="pagination">
        {% if object_list.has_previous %}
                <a href="?&page={{object_list.previous_page_number}}">Previous</a> -
        {% endif %}
                Page {{object_list.number}} / {{object_list.paginator.num_pages}}

        {% if object_list.has_next %}
                - <a href="?page={{object_list.next_page_number}}">Next</a>
        {% endif %}
    </div>
{% endif %}