我有一个Django Rest Framework的 GenericViewset,现在我想要设置分页,具体如下:
#settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':
'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20
}
#views.py
class PolicyViewSet(viewsets.GenericViewSet):
def list(self, request):
queryset = Policy.objects.all()
page = self.paginate_queryset(queryset)
serializer = PolicySerializer(page, many=True)
return self.get_paginated_response(serializer.data)
这个按预期工作。然而,如果我尝试仅使用普通的视图集来执行相同的操作,如下所示:
#views.py
class PolicyViewSet(viewsets.ViewSet):
def list(self, request):
queryset = Policy.objects.all()
page = self.paginate_queryset(queryset)
serializer = PolicySerializer(page, many=True)
return self.get_paginated_response(serializer.data)
我遇到了一个错误:
'PolicyViewSet'对象没有'paginate_queryset'属性
我如何在普通的Viewset中设置分页?DRF中的GenericViewset和Viewset有什么区别?
return self.get_paginated_response(self.paginate_queryset(serializer.data))
- Nwawel A Iroume