博客五部曲之三 - 博客RESTful


1874 浏览 5 years, 2 months

3 API Model & ListAPIView

版权声明: 转载请注明出处 http://www.codingsoho.com/

列表视图

JSON格式在web应用和IOS,Android中都广泛的使用,这将会是我们的标准格式

我们同样会实现CRUD功能 ,首先在posts下面创建api包,所有API相关的实现都会在里面实现。

参考手册 http://www.django-rest-framework.org/api-guide/generic-views/#listapiview

视图

我们新建一个目录api来处理相关的功能。创建posts.api.views.py去处理我们的视图,我们首先处理ListView,ListAPIView有很多实现参数,包括queryset,serializer_class及permission_class来实现序列号,权限控制等功能,我们会一一实现。

ListAPIView是class based view,在前面的博客中,我们主要用的是function based view。

添加视图处理函数,首先设置参数queryset,这个是要显示的实例集合,后面我们可以通过get_queryset来更新它。

from rest_framework.generics import ListAPIView
from posts.models import Post 

class PostListAPIView(ListAPIView):
    queryset = Post.objects.all()

创建api的URL文件posts.api.urls.py,对于class based view,我们调用as_view函数来做相应的处理。

from .views import (
    PostListAPIView,
    )

urlpatterns = [
    url(r'^$', PostListAPIView.as_view(), name="list"),
]

在根URL里,添加这个URL

urlpatterns = [
    url(r'^api/posts/', include("posts.api.urls",namespace="posts-api")),
]

访问 http://127.0.0.1:8000/api/posts/, 有下面报错,这个将在下一节解决

'PostListAPIView' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method