Would you like to be notified for every new articles? Please click HERE to subscribe for newsletter.

Django Pagination For Raw Query

  • Posted on: 2 February 2014
  • By: admin

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)

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.

Binary Data django-nicepaging-0.1.tar.gz17.34 KB

Add new comment

Limited HTML

  • Allowed HTML tags: <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.