Categories
Python Answers

How to use use different serializers in the same ModelViewSet with Python Django rest framework?

Spread the love

To use use different serializers in the same ModelViewSet with Python Django rest framework, we can add the get_serializer_class into a mixin.

For instance, we write

    def get_serializer_class(self):
        try:
            return self.serializer_action_classes[self.action]
        except (KeyError, AttributeError):
            return super(MultiSerializerViewSetMixin, self).get_serializer_class()

to add the get_serializer_class method.

In it, we look for serializer class in self.serializer_action_classes, which should be a dict mapping action name (key) to serializer class (value).

And if there’s no entry for that action then just fallback to the regular get_serializer_class lookup by returning self.serializer_class, DefaultSerializer.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *