S11 day 95 RestFramework 之 视图
1. 基于APIVIEW视图序列化
我们会发现两个类有好多重复的代码.所以我们引入了GenericAPIView (继承了APIView)
2.Generic ApiVIew和 ListModelMixin混合类
url路由配置
url(r'school/$', views.SchoolView.as_view(), name='article-detail'),
from rest_framework.generics import GenericAPIView from rest_framework.mixins import ListModelMixin
#学校视图(继承基础工具类阶段) class SchoolView(GenericAPIView,ListModelMixin): ''' GenericAPIView 只需要配置 queryset和serialize_class ''' queryset = models.School.objects.all() serializer_class = app01_serializer.SchoolSerializer def get(self,request,*args,**kwargs): return self.list(request,*args,**kwargs)
输出结果:
3. GenetricAPIView + RetrieveMixin 获取一条数据
url(r'^comment/(?P<pk>\d+)/$', views.CommentDetailView.as_view()),
from rest_framework.mixins import RetrieveModelMixin class CommentDetailView(GenericAPIView,RetrieveModelMixin): #mixin混合类. queryset = models.Comment.objects.all() serializer_class =app01_serializer.CommentSerializer def get(self,request,pk): return self.retrieve(request,pk)
输出结果:
4. GenericApiView + Mixin 增删改查.
# 3. 评论详情操作某一条数据 from rest_framework.mixins import RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin class CommentDetailView(GenericAPIView,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin): #mixin混合类. queryset = models.Comment.objects.all() serializer_class =app01_serializer.CommentSerializer
查: def get(self,request,pk): return self.retrieve(request,pk)
删 def delete(self,request,pk): return self.destroy(request,pk) def perform_destory(self,instance): instance.delete() 改 def put(self,request,pk): return self.update(request,pk)
输出结果:
OK
5. ListCreateAPIView和RetreveUpdateDestory
# 5 ListCreateAPIVIew 和RetreveUpdateDestory
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
class CommentView(ListCreateAPIView): #获取所有 , 添加.
queryset = models.Comment.objects.all()
serializer_class = app01_serializer.CommentSerializer
class CommentDetailView(RetrieveUpdateDestroyAPIView): #改,查和删除
queryset = models.Comment.objects.all()
serializer_class = app01_serializer.CommentSerializer
输出结果:
6. GenericViewSet ( ListCreateAPIView和RetreveUpdateDestory)
URL
url(r'^comment/$', views.CommentView.as_view({ "get":"list", "post":"create" })), url(r'^comment/(?P<pk>\d+)/$', views.CommentView.as_view({ "get":"retrieve", "put":"update", "delete":"destroy" })),
from rest_framework.viewsets import ModelViewSet class CommentViewSet(ModelViewSet): queryset = models.Comment.objects.all() serializer_class = app01_serializer.CommentSerializer