From 95b6fef56e85f454bb75545d397d5644b57efa35 Mon Sep 17 00:00:00 2001 From: Dan LaManna Date: Tue, 24 Nov 2026 10:49:16 -0500 Subject: [PATCH] Pass the paginator its count instead of patching the queryset qs_with_hardcoded_count replaced a queryset's count method with a lambda, which any clone, such as the paginator's own order_by, silently dropped, and the lesion list set a custom_count attribute with the same problem. paginate and paginate_queryset take the total as a count argument instead. A given count is returned on every page, as the lesion list already did, while queryset.count() still only runs on the first. --- isic/core/api/image.py | 19 +++++------ isic/core/pagination.py | 58 +++++++++++++++------------------- isic/core/views/collections.py | 11 ++----- isic/core/views/images.py | 15 +++++---- isic/ingest/api.py | 3 +- 5 files changed, 46 insertions(+), 60 deletions(-) diff --git a/isic/core/api/image.py b/isic/core/api/image.py index 542eb5c3..a246d863 100644 --- a/isic/core/api/image.py +++ b/isic/core/api/image.py @@ -18,7 +18,7 @@ from isic.auth import IsAuthenticated, IsStaff from isic.core.models import Image -from isic.core.pagination import CursorPagination, paginate, qs_with_hardcoded_count +from isic.core.pagination import CursorPagination, paginate from isic.core.permissions import get_visible_objects from isic.core.search import build_elasticsearch_query, facets, get_elasticsearch_client from isic.core.serializers import SearchQuerySerializer, StrictSerializer @@ -170,10 +170,7 @@ def _get_position_from_instance(self, instance, ordering): @override def paginate_queryset(self, queryset, request, *, pin_sort: bool = False, **kwargs): - # ordering clones the queryset, which would drop a hardcoded count, so a queryset that - # the view already ordered (see _ordering) is left alone. - if not queryset.query.order_by: - queryset = queryset.order_by(*_ordering(request, pin_sort=pin_sort)) + queryset = queryset.order_by(*_ordering(request, pin_sort=pin_sort)) return super().paginate_queryset(queryset, request, **kwargs) @@ -188,15 +185,15 @@ def _ordering(request, *, pin_sort: bool = False) -> tuple[str, ...]: def image_list(request): qs = get_visible_objects(request.user, "core.view_image", default_qs) + count = None if settings.ISIC_USE_ELASTICSEARCH_COUNTS: es_query = build_elasticsearch_query({}, request.user, None) - es_count = get_elasticsearch_client().count( + count = get_elasticsearch_client().count( index=settings.ISIC_ELASTICSEARCH_IMAGES_INDEX, body={"query": es_query}, )["count"] - qs = qs_with_hardcoded_count(qs, _ordering(request), es_count) - return paginate(request, qs, ImageSerializer, PinnedFirstPagination()) + return paginate(request, qs, ImageSerializer, PinnedFirstPagination(), count=count) @api_view(["GET"]) @@ -206,15 +203,15 @@ def image_search(request): search.is_valid(raise_exception=True) qs: QuerySet[Image] = search.to_queryset(user=request.user, qs=default_qs) + count = None if settings.ISIC_USE_ELASTICSEARCH_COUNTS: es_query = search.to_es_query(request.user) - es_count = get_elasticsearch_client().count( + count = get_elasticsearch_client().count( index=settings.ISIC_ELASTICSEARCH_IMAGES_INDEX, body={"query": es_query}, )["count"] - qs = qs_with_hardcoded_count(qs, _ordering(request), es_count) - return paginate(request, qs, ImageSerializer, PinnedFirstPagination()) + return paginate(request, qs, ImageSerializer, PinnedFirstPagination(), count=count) @api_view(["GET"]) diff --git a/isic/core/pagination.py b/isic/core/pagination.py index 9b70d142..13bb563e 100644 --- a/isic/core/pagination.py +++ b/isic/core/pagination.py @@ -13,25 +13,6 @@ _OFFSET_CUTOFF = 100 -def qs_with_hardcoded_count(qs: QuerySet, ordering: Sequence, count: int) -> QuerySet: - """ - Modify a queryset to return a hardcoded count rather than querying the database. - - This is useful when the count can be obtained with a cheaper method instead of - the default queryset.count() method, e.g. elasticsearch, a separate query with - fewer joins, etc. - """ - # This is an unfortunate bit of hackery to get around the fact that the CursorPagination class - # adds an order by which clones the queryset, overriding our hardcoded count. We have to repeat - # the logic here to make sure the paginator doesn't modify our queryset. - if not qs.query.order_by: - qs = qs.order_by(*ordering) - - qs.count = lambda: count - - return qs - - @dataclass class Cursor: offset: int = 0 @@ -73,8 +54,22 @@ def __init__(self, ordering: Sequence = default_ordering) -> None: self.ordering = ordering def paginate_queryset( - self, queryset: QuerySet, request: HttpRequest, *, limit: int | None, cursor: Cursor + self, + queryset: QuerySet, + request: HttpRequest, + *, + limit: int | None, + cursor: Cursor, + count: int | None = None, ) -> dict: + """ + Paginate a queryset. + + count is the total number of results, for callers that can get it cheaper than + queryset.count(), e.g. from elasticsearch or a materialized view. It's returned on every + page, whereas queryset.count() only runs on the first page since it's slow for large + queries. + """ limit = _clamp(limit or self.max_page_size, 0, self.max_page_size) if not queryset.query.order_by: @@ -82,17 +77,12 @@ def paginate_queryset( order: tuple[str, ...] = queryset.query.order_by - total_count = ( - # let the queryset define a custom_count attribute in the event that computing - # the count can be done cheaper than the default queryset.count() method. - queryset.custom_count - if hasattr(queryset, "custom_count") - else queryset.count() - # only count the total number of results if a position is absent, usually indicating - # that we're on the first page. this improves performance for larger queries. - if cursor.position is None - else None - ) + if count is not None: + total_count = count + elif cursor.position is None: + total_count = queryset.count() + else: + total_count = None base_url = request.build_absolute_uri() @@ -346,9 +336,11 @@ def validate_cursor(self, encoded_cursor: str | None) -> Cursor: return Cursor(offset=offset, reverse=reverse, position=position) -def paginate(request, queryset: QuerySet, serializer_class, paginator=None) -> Response: +def paginate( + request, queryset: QuerySet, serializer_class, paginator=None, *, count: int | None = None +) -> Response: paginator = paginator if paginator is not None else CursorPagination() params = CursorPaginationSerializer(data=request.query_params) params.is_valid(raise_exception=True) - page = paginator.paginate_queryset(queryset, request, **params.validated_data) + page = paginator.paginate_queryset(queryset, request, count=count, **params.validated_data) return Response({**page, "results": serializer_class(page["results"], many=True).data}) diff --git a/isic/core/views/collections.py b/isic/core/views/collections.py index 944e8b3b..52d23769 100644 --- a/isic/core/views/collections.py +++ b/isic/core/views/collections.py @@ -15,11 +15,7 @@ from isic.core.forms.collection import CollectionForm from isic.core.models import Collection -from isic.core.pagination import ( - CursorPagination, - CursorPaginationSerializer, - qs_with_hardcoded_count, -) +from isic.core.pagination import CursorPagination, CursorPaginationSerializer from isic.core.permissions import get_visible_objects, needs_object_permission from isic.core.services import image_metadata_csv from isic.core.services.collection import create_collection, update_collection @@ -132,8 +128,7 @@ def collection_detail(request, pk): ) # prevent the paginator from doing a slow count. - if hasattr(collection, "cached_counts"): - images = qs_with_hardcoded_count(images, ("created",), collection.cached_counts.image_count) + count = collection.cached_counts.image_count if hasattr(collection, "cached_counts") else None paginator = CursorPagination(ordering=("created",)) try: @@ -141,7 +136,7 @@ def collection_detail(request, pk): data={"limit": request.GET.get("limit", 30), "cursor": request.GET.get("cursor")} ) params.is_valid(raise_exception=True) - page = paginator.paginate_queryset(images, request, **params.validated_data) + page = paginator.paginate_queryset(images, request, count=count, **params.validated_data) except DrfValidationError as e: raise BadRequest("Invalid pagination parameters.") from e diff --git a/isic/core/views/images.py b/isic/core/views/images.py index 651b265f..cea320d3 100644 --- a/isic/core/views/images.py +++ b/isic/core/views/images.py @@ -15,7 +15,7 @@ from isic.core.api.image import PinnedFirstPagination from isic.core.forms.search import ImageSearchForm from isic.core.models import Collection, Image -from isic.core.pagination import CursorPaginationSerializer, qs_with_hardcoded_count +from isic.core.pagination import CursorPaginationSerializer from isic.core.permissions import get_visible_objects, needs_object_permission from isic.core.search import get_elasticsearch_client from isic.core.tasks import generate_staff_image_list_metadata_csv_task @@ -161,18 +161,19 @@ def image_browser(request): collections=collections, ) qs: QuerySet[Image] = Image.objects.none() - order_by = ("-pinned", "created") + total_images = 0 if search_form.is_valid(): qs = search_form.results if settings.ISIC_USE_ELASTICSEARCH_COUNTS: es_query = search_form.serializer.to_es_query(request.user) - es_count = get_elasticsearch_client().count( + total_images = get_elasticsearch_client().count( index=settings.ISIC_ELASTICSEARCH_IMAGES_INDEX, body={"query": es_query}, )["count"] - qs = qs_with_hardcoded_count(qs, order_by, es_count) + else: + total_images = qs.count() paginator = PinnedFirstPagination() try: @@ -180,7 +181,9 @@ def image_browser(request): data={"limit": request.GET.get("limit", 30), "cursor": request.GET.get("cursor")} ) params.is_valid(raise_exception=True) - page = paginator.paginate_queryset(qs, request, pin_sort=True, **params.validated_data) + page = paginator.paginate_queryset( + qs, request, pin_sort=True, count=total_images, **params.validated_data + ) except DrfValidationError as e: raise BadRequest("Invalid pagination parameters.") from e @@ -195,7 +198,7 @@ def image_browser(request): request, "core/image_browser.html", { - "total_images": qs.count(), + "total_images": total_images, "images": page["results"], "page": page, # This gets POSTed to the populate endpoint if called diff --git a/isic/ingest/api.py b/isic/ingest/api.py index f4b35e90..f53d9de9 100644 --- a/isic/ingest/api.py +++ b/isic/ingest/api.py @@ -77,8 +77,7 @@ def lesion_list(request): .order_by("id"), ) # the count can be done much more efficiently than the full query - qs.custom_count = get_lesion_count_for_user(request.user) - return paginate(request, qs, LesionSerializer) + return paginate(request, qs, LesionSerializer, count=get_lesion_count_for_user(request.user)) class AccessionCreateSerializer(StrictSerializer):