Source code for api.posts.pagination
from typing import Sequence
from django.db.models import QuerySet
from rest_framework.pagination import LimitOffsetPagination
[docs]
class SearchPagination(LimitOffsetPagination):
    """
    A custom pagination class that paginates Elasticsearch querysets.
    Uses custom offset and limit query parameters.
    """
[docs]
    def paginate_queryset(self, queryset, request, view=None):
        """
        Paginate a queryset if a `search` parameter is present in the request.
        Args:
            queryset: The queryset to paginate.
            request: The HTTP request object.
            view: The view associated with the request.
        Returns:
            The paginated queryset or the original queryset if `search` parameter is present.
        """
        search_param = request.query_params.get("search")
        self.offset = self.get_offset(request)
        self.limit = self.get_limit(request)
        self.count = self.get_count(queryset)
        self.request = request
        if search_param:
            return queryset
        return super().paginate_queryset(queryset, request, view)
[docs]
    def get_count(self, queryset: QuerySet | Sequence) -> int:
        """
        Get the count of the queryset.
        If the queryset has a `search_count` attribute, use it as the count.
        Args:
            queryset: The queryset to count.
        Returns:
            The count of the queryset.
        """
        if hasattr(queryset, "search_count"):
            return queryset.search_count
        return super().get_count(queryset)