Skip to content

Instantly share code, notes, and snippets.

@OndrejIT
Created March 19, 2019 09:59
Show Gist options
  • Save OndrejIT/8205b8737229ac223fcdf836f266012d to your computer and use it in GitHub Desktop.
Save OndrejIT/8205b8737229ac223fcdf836f266012d to your computer and use it in GitHub Desktop.
class CachedPaginator(Paginator):
"""
Paginator that does not count the rows in the table.
"""
@cached_property
def count(self):
"""Return the total number of objects, across all pages."""
try:
md5 = hashlib.md5(str(self.object_list.query).encode("utf-8")).hexdigest()
cache_key = "admin_paginator:{0}".format(md5)
counter = persistent_cache.get(cache_key) or None
if counter is None:
counter = self.object_list.count()
persistent_cache.set(cache_key, counter, timeout=3600)
except (AttributeError, TypeError):
# AttributeError if object_list has no count() method.
# TypeError if object_list.count() requires arguments
# (i.e. is of type list).
counter = len(self.object_list)
return counter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment