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