Wednesday, 18 May 2022

Django viewsets.GenericViewSet vs ModelViewSet

 https://www.django-rest-framework.org/api-guide/viewsets/#:~:text=action%20implementations%20explicitly.-,ModelViewSet,of%20the%20various%20mixin%20classes.


GenericViewSet

The GenericViewSet class inherits from GenericAPIView, and provides the default set of get_objectget_queryset methods and other generic view base behavior, but does not include any actions by default.

In order to use a GenericViewSet class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.

ModelViewSet

The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes.

The actions provided by the ModelViewSet class are .list().retrieve().create().update().partial_update(), and .destroy().

Example

Because ModelViewSet extends GenericAPIView, you'll normally need to provide at least the queryset and serializer_class attributes. For example:

class AccountViewSet(viewsets.ModelViewSet):
    """
    A simple ViewSet for viewing and editing accounts.
    """
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
    permission_classes = [IsAccountAdminOrReadOnly]

No comments:

Post a Comment