Change a field in a Django REST Framework ModelSerializer based on the request type?

后端 未结 5 2458
半阙折子戏
半阙折子戏 2021-02-19 08:13

Consider this case where I have a Book and Author model.

serializers.py

class AuthorSerializer(serializers.ModelSerializer):

         


        
5条回答
  •  长情又很酷
    2021-02-19 09:11

    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
    

提交回复
热议问题