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

标签 python rest api serialization django-rest-framework

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

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/

相关文章:

Python 子进程超时终止

Python S3 上传签名不匹配

python - 从 Voronoi 单元获取有界多边形坐标

C# (500) 内部服务器错误覆盖原始异常

api - Magento REST API 身份验证

python - 在python中获取文件的绝对路径

rest - 为 Redis 数据库构建 API REST 服务的框架?

rest - 我如何告诉我的前端后台作业已使用 Web 套接字完成?

http - REST 化 URL

Azure:如何通过 API 或 Webhook 直接连接到 IOT-Central?