或者这个任务的最佳解决方案是什么?
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
最佳答案
最简单的方法是在序列化程序上下文中发送方法并在 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
或者
如果您没有从 View 向序列化程序发送上下文,则默认情况下请求对象在上下文中发送。您也可以从那里获取它。
def update(self, instance, validated_data):
method = self.context.get('request').method
# your rest of the update method
关于python - 如何在更新 DRF 序列化器方法中确定 PATCH 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173432/