paginators.py 1.2 KB

123456789101112131415161718192021222324252627282930
  1. __package__ = 'archivebox.misc'
  2. from django.core.paginator import Paginator
  3. from django.utils.functional import cached_property
  4. class AccelleratedPaginator(Paginator):
  5. """
  6. Accellerated Pagniator ignores DISTINCT when counting total number of rows.
  7. Speeds up SELECT Count(*) on Admin views by >20x.
  8. https://hakibenita.com/optimizing-the-django-admin-paginator
  9. """
  10. @cached_property
  11. def count(self):
  12. if self.object_list._has_filters(): # type: ignore
  13. # fallback to normal count method on filtered queryset
  14. return super().count
  15. else:
  16. # otherwise count total rows in a separate fast query
  17. return self.object_list.model.objects.count()
  18. # Alternative approach for PostgreSQL: fallback count takes > 200ms
  19. # from django.db import connection, transaction, OperationalError
  20. # with transaction.atomic(), connection.cursor() as cursor:
  21. # cursor.execute('SET LOCAL statement_timeout TO 200;')
  22. # try:
  23. # return super().count
  24. # except OperationalError:
  25. # return 9999999999999