public
Created

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.