Limit items per page in Django REST Framework

11,384

Solution 1

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

Solution 2

You need to set PAGINATE_BY as doc states:

PAGINATE_BY: The default page size to use for pagination. If set to None, pagination is disabled by default

PAGINATE_BY_PARAM is for users to override the default size. So if you are afraid of its misuse just don't enable it.

PAGINATE_BY_PARAM: The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If set to None, clients may not override the default page size.

Solution 3

Better to go through Pagination

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

class ItemSetPagination(PageNumberPagination):
     page_size = 1000
     page_size_query_param = 'page_size'
     max_page_size = 10000

pagination_class = ItemSetPagination

Solution 4

Set 'MAX_PAGINATE_BY' to configure the global maximum results per page, as the doc states.

Example from the 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 configure on a per-view basis for a hard maximum limit per page.

Example from the doc:

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
Share:
11,384

Related videos on Youtube

Jarus
Author by

Jarus

keen developer focusing on web development with flask and django in python, instant messaging (xmpp), realtime web

Updated on September 14, 2022

Comments

  • Jarus
    Jarus over 1 year

    What is the best way to limit the items per page in Django REST Framework? I set PAGINATE_BY = 20 and PAGINATE_BY_PARAM. Without parameter you get 20 items but it is also possible to get 4000 items over the paginate param. This requests are very heavy and not very useful but perfect for script kiddies.

    Jarus

  • Tom Christie
    Tom Christie almost 11 years
    You're welcome to submit a pull request for a MAX_PAGINATE_BY setting.
  • Tristan
    Tristan almost 9 years
    Note that PAGINATE_BY and PAGINATE_BY_PARAM are now pending depreciation: django-rest-framework.org/api-guide/generic-views