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

Posted

技术标签:

【中文标题】Django Rest Framework:序列化程序响应错误【英文标题】:Django Rest Framework: serializer response error 【发布时间】:2019-05-23 11:33:52 【问题描述】:

我在 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

但我收到了那个错误。模型已保存,但响应给了我错误

内部服务器错误:/api/v1/checklists/3/ 回溯(最近一次通话最后): 文件“/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/django/core/handlers/exception.py”,第 41 行,在内部 响应 = get_response(请求) _get_response 中的文件“/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/django/core/handlers/base.py”,第 187 行 response = self.process_exception_by_middleware(e, request) _get_response 中的文件“/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/django/core/handlers/base.py”,第 185 行 响应 = Wrapped_callback(request, *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 行,在视图中 return 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(request, self): 文件“/home/adifilippo/.envs/accomodation/local/lib/python2.7/site-packages/rest_framework/permissions.py”,第 206 行,在 has_permission perms = self.get_required_permissions(request.method, queryset.model) AttributeError:“响应”对象没有属性“模型” "PUT /api/v1/checklists/3/HTTP/1.1" 500 42934

在此处输入代码

【问题讨论】:

你能发帖class ChecklistSerializer class ChecklistSerializer(serializers.ModelSerializer): class Meta: model = Checklist depth = 1 fields = ('id', 'approved_by', 'role', 'hardship_classification', 'total_capacity', 'capacity_for_residents '、'checklist_type'、'state'、'pdf'、'submitting_afp'、'disabled'、'location') @AmedeoDiFilippo 你能发布完整的回溯 @WillKeeling perms = self.get_required_permissions(request.method, queryset.model) AttributeError: 'Response' object has no attribute 'model' "PUT /api/v1/checklists/3/HTTP/1.1 " 500 42934 【参考方案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)

【讨论】:

我在我的项目中使用 Django 1.11 django 版本无关紧要。你为什么写它? 对不起,我是 Django 和 python 的新手。对于该方法,我在我的 urls 文件中定义了正确的 url .*py?我的 urls.py 是这样的: router.register(r'checklists', checklist.ChecklistViewSet, base_name='checklists') urlpatterns = ( url(r'^', include(router.urls)), )【参考方案2】:

你可以这样做

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)

【讨论】:

以上是关于Django Rest Framework:序列化程序响应错误的主要内容,如果未能解决你的问题,请参考以下文章

python django-rest-framework 3.3.3 更新嵌套序列化程序

django-rest-framework、多表模型继承、ModelSerializers 和嵌套序列化器

Django.rest_framework:如何序列化一对多?

Django 序列化器与 rest_framework 序列化器

Django-Rest-Framework 中的序列化程序问题

django.core 序列化器和 Django Rest Framework 序列化器之间的区别