I have a Django rest framework GenericViewset for which I am trying to set up pagination as follows:
#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)
This works as expected.However, if i try to do the same with just a normal Viewset as follows:
#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)
I get an error stating:
'PolicyViewSet' object has no attribute 'paginate_queryset'
How do i set up pagination with a normal Viewset. What is the difference between a GenericViewset and Viewset in DRF ?
Pagination is only performed automatically if you're using the generic views or viewsets
Read the docs
And to answer your second question What is the difference between a GenericViewset and Viewset in DRF
DRF has two main systems for handling views:
get, post, put, patch, and delete.ViewSet: This is an abstraction over APIView, which provides actions as methods:
list: read only, returns multiple resources (http verb: get). Returns a list of dicts.retrieve: read only, single resource (http verb: get, but will expect an id). Returns a single dict.create: creates a new resource (http verb: post)update/partial_update: edits a resource (http verbs: put/patch)destroy: removes a resource (http verb: delete)GenericViewSet: There are many GenericViewSet, the most common being ModelViewSet. They inherit from GenericAPIView and have a full implementation of all of the actions: list, retrieve, destroy, updated, etc. Of course, you can also pick some of them, read the docs.
just inherit also from GenericViewSet. For example:
#views.py
class PolicyViewSet(viewsets.ViewSet, 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With