Skip to content

Instantly share code, notes, and snippets.

@olifante
Forked from mmalone/gist:213702
Created April 14, 2010 22:05
Show Gist options
  • Save olifante/366399 to your computer and use it in GitHub Desktop.
Save olifante/366399 to your computer and use it in GitHub Desktop.
from django.core.paginator import ObjectPaginator
class QuickObjectPaginator(ObjectPaginator):
max_safe_pages = 0
def __init__(self, object_list, per_page, orphans=0, max_safe_pages=0):
self.max_safe_pages = max_safe_pages
super(QuickObjectPaginator, self).__init__(object_list, per_page, orphans)
def validate_page_number(self, page_number):
try:
page_number = int(page_number)
except:
raise InvalidPage
if page_number <= self.max_safe_pages:
return page_number
return super(QuickObjectPaginator, self).validate_page_number(page_number)
def get_page(self, page_number):
bottom = page_number * self.per_page
top = bottom + self.per_page
# get one extra object to see if there is a next page
page = list(self.object_list[bottom:top + 1])
if len(page) > self.per_page:
# if we got an extra object, update max_safe_pages
if page_number + 1 > self.max_safe_pages:
self.max_safe_pages = page_number + 1
page = page[:self.per_page]
if page_number > 0 and len(page) == 0:
raise InvalidPage
return page
def has_next_page(self, page_number):
if page_number < self.max_safe_pages:
return True
return super(QuickObjectPaginator, self).has_next_page(page_number)
def last_on_page(self, page_number):
"""
Returns the 1-based index of the last object on the given page,
relative to total objects found (hits).
"""
page_number = self.validate_page_number(page_number)
if page_number >= self.max_safe_pages:
return super(QuickObjectPaginator, self).last_on_page(page_number)
page_number += 1 # 1-base
return page_number * self.per_page
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment