我正在使用Django分页。有2个场景
我无法通过多个列表/结果集进行分页。
答案 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 %}