Pagination in Django
Most often it is necessary to paginate the results. Django comes up with a simple but pretty neat pagination out-of-the-box. Paginating is easy and simple.
Import first:
from django.core.paginator import Paginator, InvalidPage
Get the results. I read somewhere that Django delays execution of queries until necessary. If so, then this will not impact any performance.
info_list = Paginator(sol.objects.all(),paginate_by)
Now build the dictionary values to be passed to the template.
try:
page_info = info_list.page(page_num)
except InvalidPage:
page_num = 1
page_info = info_list.page(page_num)
has_previous = page_info.has_previous()
has_next = page_info.has_next()
info_dict = {
'query_list' : page_info.object_list,
'has_previous' : page_info.has_previous(),
'previous_page' : page_info.previous_page_number(),
'has_next' : page_info.has_next(),
'next_page' : page_info.next_page_number(),
'site_name' : 'sol',
'user' : request.user,
}
That is it. Now this can be called as:
{% for item in query_list %}
<tr class="itemrow">
<td class="itemcol"><a href="{{ item.get_absolute_url }}"> {{item.title}}</a></td>
<td class="itemcol">
<ul>
{% for author in item.authors.all %}
<li> <a href="{{author.get_absolute_url}}" title="{{author.name}}">{{author.name}}</a> </li>
{%endfor %}
</ul>
</td>
</tr>
{% endfor %}
This will enable pagination for the entries. Simple right?
Tags: django














Reader Comments
Use QuerySetPaginator http://www.djangoproject.com/documentation/pagination/#querysetpaginator-objects