Django休息框架modelviewsets自定义响应

时间:2018-05-05 02:47:37

标签: python django-rest-framework

我是django rest框架的新手,我必须自定义modelviewsets并序列化以在调用put方法时返回仅响应成功消息而不是queryset

1 个答案:

答案 0 :(得分:2)

您可以覆盖ModelViewSet响应来执行此操作。我假设在PUT请求的情况下,这只是 。然后你可以这样做:

class MyModelViewSet(ModelViewSet):
    def update(self, request, *args, **kwargs):
        super(MyModelViewSet, self).update(request, *args, **kwargs)
        return Response({"status": "Success"})  # Your override

这是def update的原始代码:

def update(self, request, *args, **kwargs):
    partial = kwargs.pop('partial', False)
    instance = self.get_object()
    serializer = self.get_serializer(instance, data=request.data, partial=partial)
    serializer.is_valid(raise_exception=True)
    self.perform_update(serializer)

    if getattr(instance, '_prefetched_objects_cache', None):
        # If 'prefetch_related' has been applied to a queryset, we need to
        # forcibly invalidate the prefetch cache on the instance.
        instance._prefetched_objects_cache = {}

    return Response(serializer.data)  # This is the original code

您可以在UpdateModelMixin

中的DRF找到它