Multiple Serialisers in Django ModelViewSet

how to employ different serialiser for same ModelViewSet in Django Rest Framework.

Advert

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

Comments

Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.

Last 5 Articles

All Articles >

  1. How to Deploy React JS application

     
  2. Multiple Serialisers in Django ModelViewSet

     
  3. Security Myths

     
  4. Model Design for Orders in Django

     
  5. Automating Business Operations

     

News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.