如何确定方法更新DRF序列化器中的PATCH请求

或者此任务的最佳解决方案是什么?

class MyViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    )
    serializer_class = MyViewSerializer
    pagination_class = LimitOffsetPagination
def update(self,instance,validated_data):
    instance.email = validated_data.get('email',instance.email)
    instance.content = validated_data.get('content',instance.content)
    instance.created = validated_data.get('created',instance.created)
    return instance
woshiaitade12 回答:如何确定方法更新DRF序列化器中的PATCH请求

最简单的方法是在序列化程序上下文中发送方法,并在update方法中获取它。

serialized = YourSerializer(obj,request.data,context={'method': request.method}

在您的更新功能中

def update(self,instance,validated_data):
    method = self.context.get('method')
    # your rest of the update method

如果您没有从视图向上下文发送上下文,默认情况下,请求对象是在上下文中发送的。您也可以从那里得到它。

def update(self,validated_data):
    method = self.context.get('request').method
    # your rest of the update method
,

我希望此链接有用WritableNestedModelSerializer

本文链接:https://www.f2er.com/2979156.html

大家都在问