1

I using CursorPagination of Django Rest Framework, I want to override default page_size(10) and ordering('timestamp') in a single viewset. How can I do this?

I tried with my viewset but it's not success:

from rest_framework.pagination import CursorPagination
class ListAPIView(ListAPIView):
    queryset = Cake.objects.all()
    permission_classes = [AllowAny]
    serializer_class = ListSerializer
    pagination_class = CursorPagination
    filter_backends = (OrderingFilter, DjangoFilterBackend)
    filter_class = CakeListFilter
    filterset_fields = ('cake_type', 'user__username')
    ordering = '-date'
    page_size = 5

3 Answers 3

2

You may create a new class inheriting from CursorPagination class in order to set custom page_size and/or max_page_size like so:

class CustomPageSizeCursorPagination(CursorPagination):
    page_size = 5
    max_page_size = 100

And then use this class as the pagination_class field of your viewset

WARNING: The following code is untested

Another option is to write a custom paginator class that gets the page size from the viewset. For example:

class PageSizeInViewSetCursorPagination(CursorPagination):
    def get_page_size(self, request, viewset_page_size):
        if self.page_size_query_param:
            try:
                return _positive_int(
                    request.query_params[self.page_size_query_param],
                    strict=True,
                    cutoff=self.max_page_size
                )
            except (KeyError, ValueError):
                pass

        return viewset_page_size or self.page_size

    def paginate_queryset(self, queryset, request, view=None):
        # Get the page_size from the viewset and then decide which page_size to use
        viewset_page_size = getattr(view, 'page_size', None) 
        page_size = self.get_page_size(request, viewset_page_size)


        # What follows is copy/paste of the code from CursorPagination paginate_queryset method
        if not self.page_size:
            return None

        self.base_url = request.build_absolute_uri()
        self.ordering = self.get_ordering(request, queryset, view)

        self.cursor = self.decode_cursor(request)
        if self.cursor is None:
            (offset, reverse, current_position) = (0, False, None)
        else:
            (offset, reverse, current_position) = self.cursor

        # Cursor pagination always enforces an ordering.
        if reverse:
            queryset = queryset.order_by(*_reverse_ordering(self.ordering))
        else:
            queryset = queryset.order_by(*self.ordering)

        # If we have a cursor with a fixed position then filter by that.
        if current_position is not None:
            order = self.ordering[0]
            is_reversed = order.startswith('-')
            order_attr = order.lstrip('-')

            # Test for: (cursor reversed) XOR (queryset reversed)
            if self.cursor.reverse != is_reversed:
                kwargs = {order_attr + '__lt': current_position}
            else:
                kwargs = {order_attr + '__gt': current_position}

            queryset = queryset.filter(**kwargs)

        # If we have an offset cursor then offset the entire page by that amount.
        # We also always fetch an extra item in order to determine if there is a
        # page following on from this one.
        results = list(queryset[offset:offset + self.page_size + 1])
        self.page = list(results[:self.page_size])

        # Determine the position of the final item following the page.
        if len(results) > len(self.page):
            has_following_position = True
            following_position = self._get_position_from_instance(results[-1], self.ordering)
        else:
            has_following_position = False
            following_position = None

        # If we have a reverse queryset, then the query ordering was in reverse
        # so we need to reverse the items again before returning them to the user.
        if reverse:
            self.page = list(reversed(self.page))

        if reverse:
            # Determine next and previous positions for reverse cursors.
            self.has_next = (current_position is not None) or (offset > 0)
            self.has_previous = has_following_position
            if self.has_next:
                self.next_position = current_position
            if self.has_previous:
                self.previous_position = following_position
        else:
            # Determine next and previous positions for forward cursors.
            self.has_next = has_following_position
            self.has_previous = (current_position is not None) or (offset > 0)
            if self.has_next:
                self.next_position = following_position
            if self.has_previous:
                self.previous_position = current_position

        # Display page controls in the browsable API if there is more
        # than one page.
        if (self.has_previous or self.has_next) and self.template is not None:
            self.display_page_controls = True

        return self.page

Note that in the above example the page_size from the request always takes precedence over whatever you have set up in your code. Then the viewset_page_size is the second in line and lastly the deafult page_size from the Pagination class.

7
  • If I have multiple class with multiple page_size, I have to create multi custom CursorPagination class right? Any better solution?
    – KitKit
    Jan 16, 2019 at 3:28
  • There are many ways of doing so, 1st note that the Paginator classes take into account the page number and page size that is passed through the request. Therefore one way of solving that would be to let that responsibility in the hands of the frontend.
    – ivissani
    Jan 16, 2019 at 15:48
  • If you wish to set page size in the ViewSet you need to implement a custom paginator class that overrides the def paginate_queryset(self, queryset, request, view=None) method and searches the view argument for the page_size property. Then use this new class as the paginator class of your viewsets. Will provide example in the answer
    – ivissani
    Jan 16, 2019 at 15:51
  • with class PageSizeInViewSetCursorPagination, please tell me how can I define page_size and ordering in class ListAPIView?
    – KitKit
    Jan 17, 2019 at 3:15
  • Exactly as you have them in your ListAPIView. ordering is already taken from your view by the OrderingFilter class.
    – ivissani
    Jan 17, 2019 at 17:00
1

Here is a custom pagination class that extends CursorPagination. It checks for ordering and page_size attributes defined in the viewset and if they exist use them. If not, fallback to original settings defined in the pagination class itself.

class NewsCursorPaginator(CursorPagination):
    ordering = 'title'
    page_size = 5

    # get_page_size do not have view attribute, so we have our custom one
    def get_custom_page_size(self, request, view):
        viewset_page_size = getattr(view, 'page_size', None)
        if viewset_page_size:
            self.page_size = viewset_page_size
        return super(NewsCursorPaginator, self).get_page_size(request)

    def get_ordering(self, request, queryset, view):
        viewset_ordering = getattr(view, 'ordering', None)
        if viewset_ordering:
            self.ordering = viewset_ordering
        return super(NewsCursorPaginator, self).get_ordering(request, queryset, view)

    def paginate_queryset(self, queryset, request, view=None):
        self.page_size = self.get_custom_page_size(request, view)
        return super(NewsCursorPaginator, self).paginate_queryset(queryset, request, view)
0

This implementation takes "limit" (page_size) as an optional querystring parameter.

class CursorPagination(pagination.CursorPagination):
    page_size = settings.REST_FRAMEWORK["PAGE_SIZE"]

    def get_custom_page_size(self, request, view):
        try:
            self.page_size = int(request.GET.get("limit"))
        except (ValueError, TypeError):
            pass
        return super().get_page_size(request)

    def paginate_queryset(self, queryset, request, view=None):
        self.page_size = self.get_custom_page_size(request, view)
        return super().paginate_queryset(queryset, request, view)
1
  • It ignores the max page size. I would add something like: if self.page_size > self.max_page_size or self.page_size == 0: self.page_size = self.max_page_size
    – Tycho
    Sep 25, 2022 at 19:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.