Django REST Framework different depth for POST/PUT?

前端 未结 3 831
一向
一向 2020-12-31 13:02

I am using Django REST Framework to create an API for my web app. I have a class \'Comment\', that has depth=2 set in the Meta class. This works gr

相关标签:
3条回答
  • 2020-12-31 13:38

    I believe the proper way to define a serializer field that refers to a foreign key relationship is through something like serializers.PrimaryKeyRelatedField. I don't believe that model serializers automatically use this field class without defining it explicitly in the serializer class.

    http://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfield

    I would imagine that a PrimaryKeyRelatedField serializer would correctly handle JSON data submissions like the one you used in your example.

    0 讨论(0)
  • 2020-12-31 13:45

    You can set different serializers by overriding the get_serializer_class() function, like so:

    def get_serializer_class(self): method = self.request.method if method == 'PUT' or method == 'POST': return YourWriteSerializer else: return YourReadSerializer

    I thought to add this one, since i came here from Googling after a while.

    0 讨论(0)
  • 2020-12-31 13:55

    I know this is a little bit late but I ended up using 2 serializers like so:

    class CommentReadSerializer(serializers.ModelSerializer):
        class Meta:
            model = Comment
            depth = 2
    
    class CommentWriteSerializer(serializers.ModelSerializer):
        class Meta:
            model = Comment
    

    Then used like this:

    class Comments(generics.ListCreateAPIView):
    
        model = Comment
        serializer_class = CommentReadSerializer
    
        def create(self, request, *args, **kwargs):
            serializer = CommentWriteSerializer(data=request.DATA, files=request.FILES)
            if serializer.is_valid():
                self.pre_save(serializer.object)
                self.object = serializer.save(force_insert=True)
                self.post_save(self.object, created=True)
                headers = self.get_success_headers(serializer.data)
                serializer = CommentReadSerializer(serializer.object)
                return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
    
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    0 讨论(0)
提交回复
热议问题