使用Django Rest Framework时出现了一个非常奇怪的错误。当我使用RetrieveAPIView并且发现数据时,我收到错误,当找不到数据时,我得到显示JSON的正常窗口
{
"detail": "Not found."
}
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from items.views import ItemRetrieveView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/(?P<pk>\d+)/$', ItemRetrieveView.as_view()),
]
seriliazers.py
from rest_framework import serializers
from .models import Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('pk','name','desc','created')
view.py-当我将RetrieveAPIViews更改为RetrieveUpdateDestroyAPIView时,我总是得到&#39; str&#39;即使数据不存在,对象也不可调用。
from django.shortcuts import render
from rest_framework import generics
from .models import Item
from .serializers import ItemSerializer
class ItemRetrieveView(generics.RetrieveAPIView):
lookup_field = 'pk'
queryset = Item.objects.all()
serializer_class = 'ItemSerializer'
model.py
from django.db import models
class Item(models.Model):
name = models.CharField(max_length = 30)
created = models.DateField(auto_now_add = True)
desc = models.CharField(max_length = 30)
def __str__(self):
return '%s' % (self.name)
答案 0 :(得分:3)
serializer_class = 'ItemSerializer'
将'ItemSerializer'
替换为ItemSerializer
,预期类不是字符串
serializer_class - 应该用于验证和反序列化输入以及序列化输出的序列化程序类。通常,您必须设置此属性,或覆盖get_serializer_class()方法。
get_serializer_class(个体) 返回应该用于序列化程序的类。默认返回serializer_class属性。
您可以返回课程ItemSerializer
或覆盖 get_serializer_class(self)
,如:
def get_serializer_class(self):
return ItemSerializer
答案 1 :(得分:2)
您正在为serializer_class分配字符串值。在您的代码更改
serializer_class = 'ItemSerializer'
到
serializer_class = ItemSerializer