Django分页与多个列表 [英] django pagination with multiple lists
本文介绍了Django分页与多个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Django分页.有2种情况
I am using Django pagination.There are 2 scenarios
- 当用户登陆此页面时,结果集将返回预先过滤的结果,因此我不一定需要对结果进行分页.
- 当用户关闭过滤器时,我需要显示所有结果(这是当我需要分页时,10000条记录)那些记录以不同列表的形式显示 然后将结果以压缩格式发送.
- When user lands on this page the result set returns pre-filtered results so I don't necessarily need to paginate the results.
- When user turns off filters,I need to show all results( this is when I need to paginate,10000 s of records) Those records come to view in form of different lists And I send the result as a zipped format.
我无法对1个以上的列表/结果集进行分页.
I am not able to paginate through more than 1 list/result set.
推荐答案
您需要做的就是给Paginator
对象列表
您希望在每个页面上拥有的项目数,它为您提供了访问每个页面上的项目的方法:
All you need is to give Paginator
a list of objects
The number of items you’d like to have on each page, and it gives you methods for accessing the items for each page: 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]
在模板中,您可以循环浏览以显示所有对象
in the template, you can loop through it to display all the objects
{% for obj in object_list %}
{{obj}}<br>
{% endfor %}
BONUS: How you can display Paginator almost like 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 %}
这篇关于Django分页与多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文