Override page_size in ViewSet

I am having a problem with django rest splitting. I set the pagination in the settings, for example -

'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 1 

Below is my opinion.

 class HobbyCategoryViewSet(viewsets.ModelViewSet): serializer_class = HobbyCategorySerializer queryset = UserHobbyCategory.objects.all() 

I want to set a different page size for this view. I tried setting the class variables page_size and Paginate_by, but the list is paginated according to PAGE_SIZE defined in the settings. Any idea where I'm wrong?

+5
source share
3 answers

I fixed this by creating my own pagination class. and setting the desired pages in the classroom. I used this class as pagination_class in my view.

 class ExamplePagination(pagination.PageNumberPagination): page_size = 2 class HobbyCategoryViewSet(viewsets.ModelViewSet): serializer_class = HobbyCategorySerializer queryset = UserHobbyCategory.objects.all() pagination_class=ExamplePagination 

I am not sure if there is an easier way for this. this one worked for me. But I think it is not good to create a new class, just to change page_size.

Change - a simple solution sets it as

 pagination.PageNumberPagination.page_size = 100 

in the ViewSet.

 class HobbyCategoryViewSet(viewsets.ModelViewSet): serializer_class = HobbyCategorySerializer queryset = UserHobbyCategory.objects.all() pagination.PageNumberPagination.page_size = 100 
+7
source

Use the page size query options to provide dynamic page size.

 from rest_framework.pagination import PageNumberPagination class StandardResultsSetPagination(PageNumberPagination): page_size_query_param = 'limit' 

Set default breakdown class in settings

 REST_FRAMEWORK = {'DEFAULT_PAGINATION_CLASS': 'StandardResultsSetPagination',} 

Now in your URL, specify the limit as a GET parameter.

http://example.com/list/?limit=100 or 25

+5
source

If you are trying to change the "page size" of the LimitOffsetPagination class, you must override the default_limit variable instead of page_size:

 from rest_framework import paginationclass CustomLimitOffsetPagination(pagination.LimitOffsetPagination): default_limit = 5 
+1
source

Source: https://habr.com/ru/post/1243134/


All Articles