Skip to content

Instantly share code, notes, and snippets.

@icarovirtual
Created October 19, 2019 13:04
Show Gist options
  • Save icarovirtual/e1cf8c40ead73a79d336d999d1f596dc to your computer and use it in GitHub Desktop.
Save icarovirtual/e1cf8c40ead73a79d336d999d1f596dc to your computer and use it in GitHub Desktop.
copy_queryset_without_annotations: mixins
class PaginatorWithOptimizedCount(Paginator):
@cached_property
def count(self):
try:
# First usage of optimization function
return copy_queryset_without_annotations(self.object_list).count()
except (AttributeError, TypeError):
return len(self.object_list)
class ChangeListWithOptimizedCount(ChangeList):
def get_results(self, request):
paginator = self.model_admin.get_paginator(request, self.queryset, self.list_per_page)
result_count = paginator.count
if self.model_admin.show_full_result_count:
# Seconde usage of optimization function
full_result_count = copy_queryset_without_annotations(self.root_queryset).count()
else:
full_result_count = None
can_show_all = result_count <= self.list_max_show_all
multi_page = result_count > self.list_per_page
if (self.show_all and can_show_all) or not multi_page:
result_list = self.queryset._clone()
else:
try:
result_list = paginator.page(self.page_num + 1).object_list
except InvalidPage:
raise IncorrectLookupParameters
self.result_count = result_count
self.show_full_result_count = self.model_admin.show_full_result_count
self.show_admin_actions = not self.show_full_result_count or bool(full_result_count)
self.full_result_count = full_result_count
self.result_list = result_list
self.can_show_all = can_show_all
self.multi_page = multi_page
self.paginator = paginator
class ModelAdminOptimizedMixin(object):
def get_changelist(self, request, **kwargs):
return ChangeListWithOptimizedCount
def get_paginator(self, request, queryset, per_page, orphans=0, allow_empty_first_page=True):
return PaginatorWithOptimizedCount(queryset, per_page, orphans, allow_empty_first_page)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment