Menu Close

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

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.

Posted in Python, Python Answers