27👍
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:
- APIView: This provides some handler methods, to handle the http verbs:
get
,post
,put
,patch
, anddelete
. -
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 fromGenericAPIView
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.
1👍
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)
- Spurious newlines added in Django management commands
- Django + Postgres: A string literal cannot contain NUL (0x00) characters
- How to upgrade sqlite 3.8.2 to >= 3.8.3
1👍
From the django rest-framework source code:
class ViewSet(ViewSetMixin, views.APIView):
"""
The base ViewSet class does not provide any actions by default.
"""
pass
class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
"""
The GenericViewSet class does not provide any actions by default,
but does include the base set of generic view behavior, such as
the `get_object` and `get_queryset` methods.
"""
pass
class GenericAPIView(views.APIView):
"""
Base class for all other generic views.
"""
The APIView does not contains the pagination it is implemented inside GenericAPIView
To use pagination inside ViewSet you should set the pagination class and follow the source code of GenericAPIView
The GenericAPIView contain the additional code which make it more structured. In case of usual cases GenericAPIView does the same task with less code. For complex scenarios when you want to customize more GenericAPIView would not provide any additional advantage.
0👍
How do i set up pagination with a normal Viewset?
If you want to use “pagination_class” in your viewset, so you should use GenericViewSet instead of ViewSet.
- Django media url is not resolved in 500 internal server error template
- Django querysets + memcached: best practices