一:视图
1、视图的几种方式:
(1) 第一种
from rest_framework.mixins import ListModelMixin, CreateModelMixin class PublishView(GenericAPIView, ListModelMixin, CreateModelMixin): queryset = Publish.objects.all() serializer_class = PublishSerializers def get(self, request): return self.list(request) def post(self, request): # 添加一条数据 return self.create(request)
(2) 第二种
ListCreateAPIView 继承了GenericAPIView, ListModelMixin, CreateModelMixin class PublishView(GenericAPIView, ListModelMixin, CreateModelMixin): class PublishView(ListCreateAPIView): queryset = Publish.objects.all() serializer_class = PublishSerializers
(3) 第三种
# 路由: url(r'^publish/$', views.PublishView.as_view({'get': 'list', 'post': 'create'})), url(r'^publish/(?P<pk>d+)', views.PublishView.as_view({'get': 'retrieve', 'put': 'update','delete':'destroy'})), from rest_framework.viewsets import ModelViewSet class PublishView(ModelViewSet): queryset = Publish.objects.all() serializer_class = PublishSerializers
2、最终:ViewSetMixin 它有什么作用 ?
用了它之后,视图类中不需要写get,post,put方法了,自己定义方法就可以了让请求方法对应到自己定义的方法上,配置路由
二:路由控制
1、一种基本路由:url(r'^publish/$', views.PublishView.as_view()),
2、半自动路径:views.PublishView.as_view({'get': 'list', 'post': 'create'}))
(1)必须继承:ViewSetMixin
(2)继承ViewSetMixin的先后顺序
3、全自动路由:(基本不用)
from rest_framework import routers # 生成一个router对象 router=routers.DefaultRouter() # 需要传两个参数,第一个参数就是匹配的路径,第二个参数,是视图类 router.register('publish',views.PublishView) url('', include(router.urls)), #自动生成四个路由(PublishView必须继承ModelViewSet)
三:响应器:(基本上不需要你配置)
1、局部配置
视图类中:
renderer_classes=[JSONRenderer,BrowsableAPIRenderer]
2、全局配置
在setting中:
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES':['rest_framework.renderers.JSONRenderer'] }