Skip to content

Instantly share code, notes, and snippets.

@tillgschwend
Created December 20, 2018 14:47
Show Gist options
  • Save tillgschwend/5f968ec3eb37a45cb63ebc34896a0c94 to your computer and use it in GitHub Desktop.
Save tillgschwend/5f968ec3eb37a45cb63ebc34896a0c94 to your computer and use it in GitHub Desktop.
[CachingPaginator] faster paginator that eliminates quite a few queries #performance #paginator #cache
from django.core.cache import cache
from django.core.paginator import Paginator
class CachingPaginator(Paginator):
def _get_count(self):
if not hasattr(self, "_count"):
self._count = None
if self._count is None:
try:
key = "adm:{0}:count".format(hash(self.object_list.query.__str__()))
self._count = cache.get(key, -1)
if self._count == -1:
self._count = super(Paginator).count
cache.set(key, self._count, settings.CACHED_PAGINATOR_TIMEOUT)
except:
self._count = len(self.object_list)
return self._count
count = property(_get_count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment