Django Rest Framework:序列化程序响应错误

时间:2018-12-24 08:46:34

标签: python django django-rest-framework

我在DRF中的视图集有问题:

def get_queryset(self):
    """
    :return: filtered queryset based on request query_param

    """
    # todo#amedeo: improve the readability code
    qs = super(ChecklistViewSet, self).get_queryset()
    _pk = self.kwargs['pk']

    if self.request.method == 'PUT':
        instance = qs.filter(pk=int(_pk)).first()
        # pass in the instance we want to update
        serializer = ChecklistSerializer(instance, self.request.data)

        # validate and update
        if serializer.is_valid():
            serializer.save()
            serializer_dict = serializer.data
            serializer_dict["message"] = "Checklist updated successfully."
            return response.Response(serializer_dict, status=status.HTTP_200_OK)

        else:
            return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

在我的代码中objetc已保存,但是响应给出了一个错误消息:

  

AttributeError:“响应”对象没有属性“模型”

我的序列化器是:

class ChecklistSerializer(serializers.ModelSerializer):

class Meta:
    model = Checklist
    fields = ('id', 'approved_by', 'role', 'hardship_classification',
              'total_capacity', 'capacity_for_residents', 'checklist_type',
              'state', 'pdf', 'submitting_afp', 'disabled', 'location')

我通过传递json的客户端PUT方法调用:

{
"approved_by": "Test",
"role": "test_role_4",
"hardship_classification": "test_6",
"total_capacity": "50",
"capacity_for_residents": "350",
"checklist_type": "permanent",
"state": "qcl_draft",
"pdf": null,
"submitting_afp": 3999,
"disabled": false,
"location": 97
}

但是我发现了这个错误。该模型已保存,但Response给我错误

  

内部服务器错误:/ api / v1 / checklists / 3 /   追溯(最近一次通话):     在内部的文件“ /home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/django/core/handlers/exception.py”,第41行       响应= get_response(请求)     文件_get_response中的第187行“ /home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/django/core/handlers/base.py”       响应= self.process_exception_by_middleware(e,请求)     _get_response中的文件“ /home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/django/core/handlers/base.py”,行185       响应= wraped_callback(请求,* callback_args,** callback_kwargs)     文件“ /home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/django/views/decorators/csrf.py”,第58行,在wrapped_view中       返回view_func(* args,** kwargs)     在视图中的文件“ /home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/viewsets.py”中,第116行       返回self.dispatch(request,* args,** kwargs)     派发文件“ /home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/views.py”,行495       响应= self.handle_exception(exc)     文件“ /home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/views.py”,行455,位于handle_exception中       self.raise_uncaught_exception(exc)     派发文件“ /home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/views.py”,第483行       self.initial(请求,* args,** kwargs)     最初的文件“ /home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/views.py”,第401行       self.check_permissions(请求)     文件“ /home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/views.py”,行334,在check_permissions中       如果没有permission.has_permission(请求,自我):     在has_permission中的第206行,文件“ /home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/permissions.py”       烫发= self.get_required_permissions(request.method,queryset.model)   AttributeError:“响应”对象没有属性“模型”   “ PUT / api / v1 / checklists / 3 / HTTP / 1.1” 500 42934

在此处输入代码

2 个答案:

答案 0 :(得分:1)

get_queryset方法应返回queryset而不是Response,并且在put方法中应覆盖更新操作。在此处class-based-views中阅读并 filtering了解更多详情。可能是您需要删除get_queryset覆盖并仅添加put方法,如下所示:

def put(self, request, pk, format=None):
    instance = self.get_object(pk)
    # pass in the instance we want to update
    serializer = ChecklistSerializer(instance, self.request.data)

    # validate and update
    if serializer.is_valid():
        serializer.save()
        serializer_dict = serializer.data
        serializer_dict["message"] = "Checklist updated successfully."
        return response.Response(serializer_dict, status=status.HTTP_200_OK)

    else:
        return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

答案 1 :(得分:0)

你可以这样做

from django.shortcuts import get_objects_or_404

class YourAPIView(ModelViewSet):
   def put(self, request, pk):
       instance = get_objects_or_404(YourModel, pk=pk)
       serializer = ChecklistSerializer(instance, self.request.data)

# validate and update
       if serializer.is_valid():
           serializer.save()
           serializer_dict = serializer.data
           serializer_dict["message"] = "Checklist updated successfully."
           return response.Response(serializer_dict, status=status.HTTP_200_OK)
       return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)