[Django]-Django How to paginate a list of dicts

5đź‘Ť

Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links. These classes live in django/core/paginator.py.

Give Paginator a list of objects, plus the number of items you’d like to have on each page, and it gives you methods for accessing the items for each page:

>>> from django.core.paginator import Paginator
>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2)

>>> p.count
4
>>> p.num_pages
2
>>> type(p.page_range)
<class 'range_iterator'>
>>> p.page_range
range(1, 3)

>>> page1 = p.page(1)
>>> page1
<Page 1 of 2>
>>> page1.object_list
['john', 'paul']

>>> page2 = p.page(2)
>>> page2.object_list
['george', 'ringo']
>>> page2.has_next()
False
>>> page2.has_previous()
True
>>> page2.has_other_pages()
True
>>> page2.next_page_number()
Traceback (most recent call last):
...
EmptyPage: That page contains no results
>>> page2.previous_page_number()
1
>>> page2.start_index() # The 1-based index of the first item on this page
3
>>> page2.end_index() # The 1-based index of the last item on this page
4

>>> p.page(0)
Traceback (most recent call last):
...
EmptyPage: That page number is less than 1
>>> p.page(3)
Traceback (most recent call last):
...
EmptyPage: That page contains no results

I hope these example code snippets helps resolving your query!

2đź‘Ť

My suggestion is using datatables.net

It’s very easy to install and still the pagination will be done in the frontend.

Simply add

<link rel="stylesheet" href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />

<script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"> </script> 

Also, do not forget to add jQuery.

Then just call a simple jQuery function

$(document).ready( function () {
    $('#myTable').DataTable();
} );

0đź‘Ť

You can use basically DRF, overriding the class-based view ModelViewSet , adding the pagination class.You can then easily customize the pagination displaying 100, 20, 10 and so forth.

from rest_framework import views, viewsets, authentication, permissions,pagination   
class  A (viewsets.ModelViewSet):
          pagination_class = pagination.PageNumberPagination
          page_size = 100

       def get_questions(self, request, *args, **kwargs):
           #Your code here 
           #intercete the code and inject this here
           if request.GET.get('page', None) is not None:
              self.page_size = request.GET.get('page_size',self.page_size)
              page = self.paginate_queryset(self.queryset.order_by(order_by))
           else:
               #Something else

Leave a comment