JayK23
JayK23

Reputation: 253

How can i set custom pagination in Django Rest Framework?

I'm trying to set a custom pagination for my API endpoint, where if there is a filter in the URL, Django must return a specific amount of records, and another amount of records if there isn't any filter.

I have the following code:

valid_filters = {'Name', 'Date'}
def _has_valid_filters(iterable):
    return not valid_filters.isdisjoint(iterable)

class MyPagination(LimitOffsetPagination):
    def get_page_size(self, request):
        if _has_valid_filters(request.query_params.items()):
            return 15
        else:
            return 30

class MyView(viewsets.ModelViewSet):
    pagination_class = MyPagination
    http_method_names = ['get']
    serializer_class = My_Serializer
    
    def get_queryset(self):
        valid_filters = {
            'Name': 'Name',
            'Date': 'Date__gte',
        }

        filters = {valid_filters[key]: value for key, value in self.request.query_params.items() if key in valid_filters.keys()}

        queryset = Model.objects.filter(**filters)

        return queryset

The problem with this code is that the pagination is always the same. While MyPagination is called, it looks like get_page_size is never called for some reason. Can anyone help me out on this?

Upvotes: 2

Views: 1249

Answers (1)

rob
rob

Reputation: 2146

I don't think LimitOffsetPagination has a method named get_page_size so it would never be called. I believe what you want is get_limit().

That said, I think this is a bit to unRESTful to obscure page limit in this way and I believe this should just be controlled by the query parameters fed by the client.

Upvotes: 1

Related Questions