简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM