Django Rest框架 - 如果表包含响应显示服务器错误(500)的数据

Posted

技术标签:

【中文标题】Django Rest框架 - 如果表包含响应显示服务器错误(500)的数据【英文标题】:Django Rest framework - If table contains data in response showing Server Error (500) 【发布时间】:2016-03-10 04:46:14 【问题描述】:

我正在使用 DjangoRestFramework 进行休息 api

在获取请求中 如果表中没有数据,则响应显示为空。 如果表中有数据,则响应显示空服务器错误 (500)。

以下是我的代码

models.py

from __future__ import unicode_literals
from django.db import models

# Create your models here.
class Employee(models.Model):
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=200)

序列化器.py

from rest_framework import serializers
from firstexample.models import Employee

class employeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = ('name', 'address')

views.py

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets
from firstexample.models import Employee
from firstexample.serializers import employeeSerializer
# Create your views here.


class employeeList(APIView):

    def get(self, request, format=None):
        employees = Employee.objects.all()
        serializer = employeeSerializer(employees, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = employeeSerializer(data=request.data)
        print(request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

urls.py

from django.conf.urls import url
from django.contrib import admin
from firstexample import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^employeesList/$', views.employeeList.as_view()),
]

谁能帮帮我。我花了更多时间在这上面,但我没有弄清楚这个问题。

提前致谢。

错误代码

Performing system checks...

System check identified no issues (0 silenced).
December 05, 2015 - 07:50:03
Django version 1.10.dev20151112003354, using settings 'helloworld.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
<QuerySet [<Employee: Employee object>]>
Internal Server Error: /employeesList/
Traceback (most recent call last):
  File "/Users/jaikakkar/Desktop/Python/django/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/jaikakkar/Desktop/Python/django/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/jaikakkar/Desktop/Python/django/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/jaikakkar/Desktop/Python/django/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
    response = self.handle_exception(exc)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/jaikakkar/Desktop/pythonlearning/helloworld/firstexample/views.py", line 17, in get
    print(serializer.data)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/serializers.py", line 674, in data
    ret = super(ListSerializer, self).data
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/serializers.py", line 239, in data
    self._data = self.to_representation(self.instance)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/serializers.py", line 614, in to_representation
    self.child.to_representation(item) for item in iterable
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/serializers.py", line 459, in to_representation
    fields = self._readable_fields
  File "/Users/jaikakkar/Desktop/Python/django/django/utils/functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/serializers.py", line 353, in _readable_fields
    field for field in self.fields.values()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/serializers.py", line 339, in fields
    for key, value in self.get_fields().items():
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/serializers.py", line 918, in get_fields
    info = model_meta.get_field_info(model)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/utils/model_meta.py", line 69, in get_field_info
    reverse_relations = _get_reverse_relationships(opts)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/rest_framework/utils/model_meta.py", line 137, in _get_reverse_relationships
    for relation in opts.get_all_related_objects():
AttributeError: 'Options' object has no attribute 'get_all_related_objects'
[05/Dec/2015 07:50:04] "GET /employeesList/ HTTP/1.1" 500 114115

【问题讨论】:

为什么在使用序列化程序的同时使用format=None?尝试从您的get 中删除format=None,看看它是如何工作的。 感谢您的回复。删除了 format=None 但仍然出现相同的错误。 控制台堆栈跟踪中有什么?在配置中设置 debug=True 并向我们展示详细信息 博士需要 django 1.7+ 您的另一个潜在问题是库的位置 - DRF 位于 /Library 中,而 Django 位于 /Desktop/Python/... (在第一种情况下使用 sudo 完成安装的混合)。我建议您在某个时候注意这一点 - 坚持使用 brew/pip 并且永远不要使用 sudo 安装。这是一个很好的:***.com/questions/26917765/… 【参考方案1】:

DRF 3+ 版不适用于 Django 1.1(在您上面的堆栈跟踪中),它需要 Django 1.7+。升级到最新版本的 Django 并从您视图中的 .get() 方法中删除 format=None

【讨论】:

我用 django1.9 和 drf3.3.1 创建了虚拟环境,现在请求和响应工作完美,非常感谢您的帮助。我认为问题还在于您在评论中提到的 Drf 位于 /Library 和 Django 位于 /desktop/Python 中。

以上是关于Django Rest框架 - 如果表包含响应显示服务器错误(500)的数据的主要内容,如果未能解决你的问题,请参考以下文章

Django rest框架:如何全局更改错误响应格式

django rest 框架:从序列化器 validate() 方法设置字段级错误

Django REST框架-请求与响应

如何覆盖 RetrieveAPIView 响应 django rest 框架

为啥从 django rest 框架返回的 JSON 在响应中有正斜杠?

django rest框架列表查询自定义json数组结果响应,因为日期格式