接上文 这里先写一个GET请求的
1.先在VIEW里定义一个方法 代码如下:
@api_view(['GET', 'POST'])
def book_request(request):
if request.method == 'GET':
queryset = Book.objects.all()
serializer_class = BookSerializer
serializer = BookSerializer(queryset)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response({'key': 'value'}, status=status.HTTP_200_OK)
这里的BookSerializer是上文定义的,注意
serializer = BookSerializer(queryset)
return Response(serializer.data, status=status.HTTP_201_CREATED)
此处2行与上一篇文不一样,这里如果没有返回会提示
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<type 'NoneType'>`
2.url里加上路由规则
url(r'^test/',include('quickstart.urls')),
quickstart.urls:
from django.conf.urls import *
from rest_framework.views import *
urlpatterns = patterns('quickstart.views',
url(r'^$', 'book_request')
)
3.启动
http://localhost:8000/test/
提示错误:'QuerySet' object has no attribute 'id'
但是序列化里已经有了这个字段了,后来想起官网API里序列化这一节有写,果然如果处理的是集合那么应该为
serializer = BookSerializer(queryset,many=True)
这个时候就可以正常了。
其实我看这个rest_framwwork 只是为机器学习相关内容做铺垫,所以只是略微实现,如果要用请自行补充,博文只记录易错点。