14๐
โ
You can achieve something relatively clean:
- Assuming you are setting the pagination per class with the
pagination_class
attribute. - Assuming that you keep the
page_size
attribute in your class.
-
In your
settings.py
add a global pagination setting:'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': default_page_size,
You can handle with this all the views that have the same page size.
-
For any other view/viewset:
class ACustomViewSet(mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): pagination_class = PageNumberPagination page_size = N pagination_class.page_size = self.page_size
Or you can do this inside a method:
def list(self, request, *args, **kwargs): self.pagination_class.page_size = self.page_size ...
๐คJohn Moutafis
3๐
I finally ended up with customizing it in a custom pagination. It seemed like the most neat and least hacky solution.
The custom pagination
from rest_framework import pagination
class CustomPageNumberPagination(pagination.PageNumberPagination):
"""Custom page number pagination."""
page_size = 30
max_page_size = 10000
page_size_query_param = 'page_size'
def get_page_size(self, request):
"""Get page size."""
# On certain pages, force custom/max page size.
try:
view = request.parser_context['view']
if view.action in [
'custom_page_size_view_1',
'custom_page_size_view_2',
# ...
'custom_page_size_view_n',
]:
return self.max_page_size
except:
pass
return super(CustomPageNumberPagination, self).get_page_size(request)
The view
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import list_route
from .pagination import CustomPageNumberPagination
class MyView(ModelViewSet):
pagination_class = CustomPageNumberPagination
@list_route()
def custom_page_size_view_1(self, request):
"""Custom page size view 1"""
@list_route()
def custom_page_size_view_2(self, request):
"""Custom page size view 2"""
@list_route()
def custom_page_size_view_3(self, request):
"""Custom page size view 3"""
๐คArtur Barseghyan
- How should I represent a bit flags int field in django admin?
- Python logging to multiple files
- Django: how to filter() after distinct()
- Django admin custom ArrayField widget
- Where should you update Celery settings? On the remote worker or sender?
Source:stackexchange.com