博客五部曲之三 - 博客RESTful


1582 浏览 5 years, 9 months

6 DetailView

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

DetailView

RetrieveAPIView对应的就是DetailView

参考网站为http://www.django-rest-framework.org/api-guide/generic-views/#retrieveapiview

对应视图函数为

class PostDetailAPIView(RetrieveAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

在url里添加路由

urlpatterns = [
    url(r'^(?P<pk>\d+)/$', PostDetailAPIView.as_view(), name="detail"),

访问http://127.0.0.1:8000/api/posts/1/,即可以看到返回信息

效果图如下

lookup_field

上面的路由用了pk作为参数,我们也可以slug, 这需要用到lookup_field。配置如下

class PostDetailAPIView(RetrieveAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    lookup_field = "slug"

urlpatterns = [
    url(r'^(?P<slug>[\w-]+)/$', PostDetailAPIView.as_view(), name="detail"),

新的访问链接为http://127.0.0.1:8000/api/posts/new-post/

lookup_url_kwarg

如果想给url参数设置特别名字,可以用lookup_url_kwarg参数。
- lookup_url_kwarg - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as lookup_field.

修改后代码如下

class PostDetailAPIView(RetrieveAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    lookup_field = "slug"
    lookup_url_kwarg = "slugurl"

urlpatterns = [
    url(r'^(?P<slugurl>[\w-]+)/$', PostDetailAPIView.as_view(), name="detail"),

最后,可以通过PostSerializer修改修改或扩展返回的字段。我们也可以定义两个不同的PostSerializer,来满足ListView和RetrieveView的不同需求