Django Pagination For Raw Query
It's almost two weeks since I started to learn Django until this article is written. It's true that Django has a very powerfull pagination function. When we use it with QuerySet, the query result won't be fetched until we print the result. Yeah, it really saves the performance, but when we use it together with the raw query, all the query result will be fetched first then the library will perform the pagination on it. To solve the problem, I try to create the custom pagination class for Django. This class is inspired by my PHP version class for pagination. Because I'm still new in Django, please leave a comment or contact me if you have any suggestion or find any weaknesses in this library.
So, how to use this class? First you have to download the library archive from the attachment below. Then you can install it using pip.
pip install --user django-nicepaging-0.1.tar.gz
That command will install the nicePaging as new python application. After we install it, let's try this application from the Django shell.
from nicepaging.nicePaging import nicePaging p = nicePaging() cursor = p.pager_query("SELECT * FROM table", [], 10, 1) cursor.fetchall()
The simplest use in your views.py file can be done in the following way.
from django.http import HttpResponseRedirect, HttpResponse from django.template import RequestContext, loader from nicepaging.nicePaging import nicePaging def index(request): p = nicePaging() current_page = 1; if request.GET.get('page') : current_page = int(request.GET['page']) # Pass the following arguments : sql statement, sql parameter (in array), # number of rows per page, and the current page result = p.pager_query("SELECT * FROM polls_poll", [], 10, current_page) template = loader.get_template('polls/index.html') context = { 'list': result, # Display the pager link 'pager': p.create_paging(""), } return render(request, 'polls/index.html', context)
This is how the pagination will look like:
The more detail example in using this library is available in the attachment.
Attachment | Size |
---|---|
django-nicepaging-0.1.tar.gz | 17.34 KB |
Add new comment