Limit the number of elements per page in the Django REST Framework

What is the best way to limit elements on a page in the Django REST Framework? I set PAGINATE_BY = 20 and PAGINATE_BY_PARAM. Without a parameter, you get 20 elements, but it is also possible to get 4000 elements by the paginate parameter. These queries are very heavy and not very useful, but perfect for a kids script.

Jarus

+7
rest api django django-rest-framework
source share
4 answers

If you want to set a hard maximum limit, look at overriding the get_paginate_by method to general views.

+5
source share

You need to set PAGINATE_BY as doc :

PAGINATE_BY . The default page size used for pagination. If set to No, paging is disabled by default.

PAGINATE_BY_PARAM designed to allow users to override the default size. Therefore, if you are afraid of its misuse, just do not turn it on.

PAGINATE_BY_PARAM : the name of the query parameter that can be used by the client overrides the default page size used for pagination. If set to No, clients cannot override the default page size.

+5
source share

Set 'MAX_PAGINATE_BY' to configure global maximum results per page, as indicated by doc .

Example from doc :

 REST_FRAMEWORK = { 'PAGINATE_BY': 10, # Default to 10 'PAGINATE_BY_PARAM': 'page_size', # Allow client to override, using `?page_size=xxx`. 'MAX_PAGINATE_BY': 100 # Maximum limit allowed when using `?page_size=xxx`. } 

Set max_paginate_by to view-based settings for a hard maximum page limit.

Example from the document:

 class PaginatedListView(ListAPIView): queryset = ExampleModel.objects.all() serializer_class = ExampleModelSerializer paginate_by = 10 paginate_by_param = 'page_size' # Set MAX results per page max_paginate_by = 100 
+3
source share

Better go through Pagination

The PageNumberPagination class includes a number of attributes that can be overridden to change the pagination style.

 class ItemSetPagination(PageNumberPagination): page_size = 1000 page_size_query_param = 'page_size' max_page_size = 10000 pagination_class = ItemSetPagination 
+3
source share

All Articles