Skip to content

Instantly share code, notes, and snippets.

@Trafitto
Forked from hakib/time_limited_paginator.py
Created October 12, 2023 13:43
Show Gist options
  • Save Trafitto/1b11dd1a31e8fd37476b4dbc8422c2e9 to your computer and use it in GitHub Desktop.
Save Trafitto/1b11dd1a31e8fd37476b4dbc8422c2e9 to your computer and use it in GitHub Desktop.
CountTimeoutLimitPaginator - Paginator that enforced a timeout on the count operation.
class TimeLimitedPaginator(Paginator):
"""
Paginator that enforced a timeout on the count operation.
When the timeout is reached a "fake" large value is returned instead,
Why does this hack exist? On every admin list view, Django issues a
COUNT on the full queryset. There is no simple workaround. On big tables,
this COUNT is extremely slow and makes things unbearable. This solution
is what we came up with.
"""
@cached_property
def count(self):
# We set the timeout in a db transaction to prevent it from
# affecting other transactions.
with transaction.atomic(), connection.cursor() as cursor:
cursor.execute('SET LOCAL statement_timeout TO 200;')
try:
return super().count
except OperationalError:
return 9999999999
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment