「Django」rest_framework学习系列-视图
方式一
1.settings设置
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
INSTALLED_APPS = [ ... 'rest_framework', ]
2.views设置
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from rest_framework.response import Response class PagesView(APIView): def get(self,request,*args,**kwargs): ... ... return Response(ser.data)
方式二
1.urls:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
re_path(r'^(?P<version>[v1|v2]+)/pages/$',PagesView.as_view({'get':'list'}),),
2.views:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from rest_framework.viewsets import GenericViewSet get请求执行list方法 class PagesView(GenericViewSet): queryset = models.UserInfo.objects.all() serializer_class = pages.PagesSerializer #自己写好的类 pagination_class = MyPageNumberPagination #同上 def list(self,request,*args,**kwargs): # 获取所有数据 m = self.get_queryset() #创建分页对象并在数据库中获取分页的数据 pa_info = self.paginate_queryset(m) #对数据进行序列化 ser = self.get_serializer(instance=pa_info,many=True) return Response(ser.data)
方式三
1.urls:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
re_path(r'^(?P<version>[v1|v2]+)/pages/$',PagesView.as_view({'get':'list','post':'create'}),), re_path(r'^(?P<version>[v1|v2]+)/pages/(?P<pk>\d+)$', PagesView.as_view({'get': 'retrieve', 'delete': 'destroy','put':'update','patch':'partial_update'}), ),
2.views:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from rest_framework.viewsets import ModelViewSet(继承了6个类,继承越多,代码需要写的越少) from rest_framework.mixins import ListModelMixin,CreateModelMixin(被上面的类继承) class PagesView(ModelViewSet): queryset = models.UserInfo.objects.all() serializer_class = pages.PagesSerializer pagination_class = MyPageNumberPagination 总结: a.增删改查用方式三 b.增删 ListModelMixin/CreateModelMixin,GenericViewSet c.复杂逻辑 GenericViewSet或APIView