Consider this case where I have a Book
and Author
model.
serializers.py
class AuthorSerializer(serializers.ModelSerializer):
You are looking for the get_serializer_class
method on the ViewSet
. This allows you to switch on request type for which serializer that you want to use.
from rest_framework import viewsets
class MyModelViewSet(viewsets.ModelViewSet):
model = MyModel
queryset = MyModel.objects.all()
def get_serializer_class(self):
if self.action in ('create', 'update', 'partial_update'):
return MySerializerWithPrimaryKeysForCreatingOrUpdating
else:
return MySerializerWithNestedData