django pagination with multiple lists

穿精又带淫゛_ 提交于 2020-01-25 10:08:14

问题


I am using Django pagination.There are 2 scenarios

  1. When user lands on this page the result set returns pre-filtered results so I don't necessarily need to paginate the results.
  2. 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.

I am not able to paginate through more than 1 list/result set.


回答1:


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 %}


来源:https://stackoverflow.com/questions/50217542/django-pagination-with-multiple-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!