问题描述
我有django休息框架分页的问题。我已经在如下设置中设置了分页:
'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE':1
以下是我的观点。
class HobbyCategoryViewSet(viewsets.ModelViewSet):
serializer_class = HobbyCategorySerializer
queryset = UserHobbyCategory.objects.all ()
我想为此视图设置不同的页面大小。我已经尝试设置page_size和Paginate_by类变量,但列表是按照设置中定义的PAGE_SIZE分页的。任何想法我错了吗?
我通过创建自定义分页课来修复这个问题。并在课堂上设置所需的pagesize。我在我的视图中使用了这个类作为pagination_class。
class ExamplePagination(pagination.PageNumberPagination):
page_size = 2
class HobbyCategoryViewSet(viewsets.ModelViewSet):
serializer_class = HobbyCategorySerializer
queryset = UserHobbyCategory.objects.all()
pagination_class = ExamplePagination
我不知道是否有更容易的方法。这一个为我工作。但是,我觉得创建新类只是为了更改page_size不好。
编辑 - 简单的解决方案设置为
ViewSet中的
pagination.PageNumberPagination.page_size = 100
class HobbyCategoryViewSet(viewsets.ModelViewSet):
serializer_class = HobbyCategorySerializer
queryset = UserHobbyCategory.objects。 all()
pagination.PageNumberPagination.page_size = 100
I am having problem with django rest framework pagination.I have set pagination in settings like -
'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 1
Below is my viewset.
class HobbyCategoryViewSet(viewsets.ModelViewSet):
serializer_class = HobbyCategorySerializer
queryset = UserHobbyCategory.objects.all()
I want to set different page size for this viewset. I have tried setting page_size and Paginate_by class variables but list is paginated according to PAGE_SIZE defined in settings. Any idea where I am wrong ?
I fixed this by creating custom pagination class. and setting desired pagesize in class. I have used this class as pagination_class in my viewset.
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 any easier way for this. this one worked for me. But I think its not good to create new class just to change page_size.
Edit - simple solution is set it like
pagination.PageNumberPagination.page_size = 100
in ViewSet.
class HobbyCategoryViewSet(viewsets.ModelViewSet):
serializer_class = HobbyCategorySerializer
queryset = UserHobbyCategory.objects.all()
pagination.PageNumberPagination.page_size = 100
这篇关于Django rest框架在ViewSet中覆盖page_size的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!