Django:RestFramework之-------视图
10.视图
-
GenericAPIView封装一些方法,将这些方法返回值放在类变量位置上.
1.GenericAPIView视图示例:不怎么用
from api.utils.serializers.pager import PagerSerialiser
from rest_framework.generics import GenericAPIView
class VView(GenericAPIView):
#获取模型类
queryset = models.Role.objects.all()
#序列化器
serializer_class = PagerSerialiser
#分页设置
pagination_class = PageNumberPagination
def get(self,request,*args,**kwargs):
roles = self.get_queryset()#获得数据
#分页获取
pager_roles = self.paginate_queryset(roles)
#序列化
ser = self.get_serializer(instance=pager_roles,many=True)
return Response(ser.data)
2.GenericViewSet视图类
- 实现自定义路由执行函数
#urls.py
#get方法过来执行VView get请求执行list方法. post请求执行tijiao
url(r'^(?P<version>[v1|v2]+)/vview/$', views.VView.as_view({"get":"list","post":"tijiao"}),),
#视图函数:
from rest_framework.viewsets import GenericViewSet
class VView(GenericViewSet):
#获取模型类
queryset = models.Role.objects.all()
#序列化器
serializer_class = PagerSerialiser
#分页设置
pagination_class = PageNumberPagination
def list(self,request,*args,**kwargs):
roles = self.get_queryset()#获得数据
#分页获取
pager_roles = self.paginate_queryset(roles)
#序列化
ser = self.get_serializer(instance=pager_roles,many=True)
return Response(ser.data)
def tijiao(self,request,*args,**kwargs):pass
3.ListModelMixin 封装get请求
4.CreateModelMixin 自带post请求
#urls.py
url(r'^(?P<version>[v1|v2]+)/vview/$', views.VView.as_view({"get":"list","post":"create"}),),
#GenericViewSet自定义request.methods处理方法,在url上设置
#视图函数:
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin,CreateModelMixin
class VView(ListModelMixin,CreateModelMixin,GenericViewSet):
#获取模型类
queryset = models.Role.objects.all()
#序列化器
serializer_class = PagerSerialiser
#分页设置
pagination_class = PageNumberPagination
5.ModelViewSet
- 让你的代码变得简单舒服
- ModelViewSet继承了前面所有类的功能
#urls.py
#设置{"get":"list"} 内置封装好了方法返回所有数据
url(r'^(?P<version>[v1|v2]+)/vview/$', views.VView.as_view({"get":"list"}),),
url(r'^(?P<version>[v1|v2]+)/vview/(?P<pk>\d+)/$', views.VView.as_view(
{"get":"retrieve","delete":"destroy","put":"update","patch":"partial_update"}),
),
"""
"get":"retrieve" 获取单个数据 访问URL:http://127.0.0.1:8000/api/v1/vview/2/
"delete":"destroy" 删除单个数据
"put":"update" 更新一条数据
"patch":"partial_update" 修改一条数据
"""
from rest_framework.viewsets import ModelViewSet
class VView(ModelViewSet):
#获取模型类
queryset = models.Role.objects.all()
#序列化器
serializer_class = PagerSerialiser
#分页设置
pagination_class = PageNumberPagination
- 显示效果
6.总结
1.基本增删改查用ModelViewSet
2.只有增删 CreateModelMixin,DestroyModelMixin,GenericViewSet
3.复杂增删改查,可以使用GenericViewSet 或 APIView
-
知识拓展
GenericViewSet.get_object 只有调用get_object check_object_permissions 用于判断你这个用户对这个对象是否有调用权限. has_object_permission 才会生效此方法