Skip to content

Instantly share code, notes, and snippets.

@antonioj-mattos
Forked from ketanbhatt/admin.py
Created April 2, 2020 03:54
Show Gist options
  • Save antonioj-mattos/8f24398d3fe5da8914dc099662417cfb to your computer and use it in GitHub Desktop.
Save antonioj-mattos/8f24398d3fe5da8914dc099662417cfb to your computer and use it in GitHub Desktop.
from django.contrib.admin import ModelAdmin
class MyTableAdmin(ModelAdmin):
...
paginator = LargeTablePaginator
...
from django.core.paginator import Paginator
class LargeTablePaginator(Paginator):
"""
Warning: Postgresql only hack
Overrides the count method of QuerySet objects to get an estimate instead of actual count when not filtered.
However, this estimate can be stale and hence not fit for situations where the count of objects actually matter.
"""
def _get_count(self):
if getattr(self, '_count', None) is not None:
return self._count
query = self.object_list.query
if not query.where:
try:
cursor = connection.cursor()
cursor.execute("SELECT reltuples FROM pg_class WHERE relname = %s",
[query.model._meta.db_table])
self._count = int(cursor.fetchone()[0])
except:
self._count = super(LargeTablePaginator, self)._get_count()
else:
self._count = super(LargeTablePaginator, self)._get_count()
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