Django ModelViewSet is a straight forward way for CRUD with a Single serialiser, but there can be instances where you need to use different serialisers for create function or any other.

You have two options.

  1. Define a function to override functions of ModelViewSet and use different serialiser inside the function.
  2. Use get_serializer_class to provide different serialiser depending on the request method.

Overriding function

In here create overrides the default object class of ModelViewSet and rest Is defined in the function.


class YourModelViewSet(viewsets.ModelViewSet):
    queryset = YourModel.objects.filter()
    serializer_class = YourModelSerializer
    permission_classes = (permissions.IsAuthenticated)

    def create(self):
       serializer = YourModelSerializer_2(data=request.data)
       yourdata = serialiser.save()

get_serializer_class

If you don’t want to mess up the pre-packed functions of DRF but want each request to use a different serialiser this is the way to go.


class YourModelViewSet(viewsets.ModelViewSet):
    queryset = YourModel.objects.filter()
    serializer_class = YourModelSerializer
    permission_classes = (permissions.IsAuthenticated)

    def get_serializer_class(self):
        if self.action == 'list':
            return YourModelSerializer_2
        return YourModelSerializer