4. 视图组件
本节内容
一、 2个视图基类
二 、
3.6 RetrieveUpdateAPIView ( 补充扩展)
3.7 RetrieveUpdateDestoryAPIView ( 补充扩展)
四、视图集基类ViewSet
视图
-
控制序列化器的执行(检验、保存、转换数据)
-
一、 2个视图基类
#rest_framework.views.APIView from rest_framework.views import APIView
-
-
视图方法可以返回REST framework的
Response
对象,视图会为响应数据设置(render)符合前端要求的格式; -
任何
APIException
异常都会被捕获到,并且处理成合适的响应信息; -
-
authentication_classes 列表或元祖,身份认证类
-
permissoin_classes 列表或元祖,权限检查类
-
throttle_classes
- 查询所有数据
- 添加一条记录
- 查询单条记录
- 修改一条记录
- 删除一条记录
from app01 import models from rest_framework import serializers # 模型序列化器类 class StudentModelSerializer(serializers.ModelSerializer): class Meta: model = models.Student fields = '__all__' extra_kwargs = { 'id': {'read_only':True}, }
from rest_framework.views import APIView from app01 import models from rest_framework.response import Response # ######APIView的接口######### class StudentsView(APIView): # 查询所有数据 def get(self,request): print(type(request.POST)) students = models.Student.objects.all() serialzer_obj = StudentModelSerializer(instance=students,many=True) return Response(serialzer_obj.data) # 添加一条记录 def post(self, request): data = request.data serialzer_obj = StudentModelSerializer(data=data) if serialzer_obj.is_valid(): obj = serialzer_obj.save() serialzer_obj = StudentModelSerializer(instance=obj) return Response(serialzer_obj.data) else: return Response({'error':'添加失败'}) class StudentView(APIView): def get(self,request, pk): obj = models.Student.objects.get(pk=pk) serialzer_obj = StudentModelSerializer(instance=obj) return Response(serialzer_obj.data) def put(self, requset, pk): # id=pk # pk=pk old_obj = models.Student.objects.get(pk=pk) data = requset.data serialzer_obj = StudentModelSerializer(instance=old_obj, data=data,partial=True) if serialzer_obj.is_valid(): obj = serialzer_obj.save() serialzer_obj = StudentModelSerializer(instance=obj) return Response(serialzer_obj.data) else: return Response({'error':'更新失败'}) def delete(self,request,pk): models.Student.objects.filter(pk=pk).delete() return Response('')
对应的urls.py
from django.urls import path,re_path from . import views urlpatterns = [ path(r'students/',views.StudentsAPIView.as_view()), re_path(r'students/(?P<pk>\d+)/',views.StudentAPIView.as_view()), ]
# rest_framework.generics.GenericAPIView from rest_framework.generics import GenericAPIView
-
serializer_class
方法
- get_serializer_class(self)
当出现一个视图类中调用多个序列化器时,那么可以通过条件判断在get_serializer_class方法中通过返回不同的序列化器类名就可以让视图方法执行不同的序列化器对象了。
# 如果是post请求,我使用StudentModelSerializer # get请求的话: 我使用Student2ModelSerializer def get_serializer_class(self): #self.request #-- 当前请求对象 if self.request.method == 'GET': return Student2ModelSerializer else: return StudentModelSerializer
比如serializer = self.get_serializer(instance=self.get_object(),context={'pk':pk})
,下面的request和view我们后面会用到,现在先了解一下,后面使用就知道了
-
request 当前视图的请求对象
-
view 当前请求的类视图对象
-
提供的关于数据库查询的属性与方法
-
queryset
方法:
- get_queryset(self)
def get_queryset(self): user = self.request.user return user.accounts.all()
- get_object(self)
返回详情视图所需的模型类数据对象,主要用来提供给Mixin扩展类使用
在试图中可以调用该方法获取详情信息的模型类对象
若详情访问的模型类对象不存在,会返回404
该方法会默认使用APIView提供的check_object_permissions方法检查当前对象是否有权限被访问
举例:
# url(r'^books/(?P<pk>\d+)/$', views.BookDetailView.as_view()), class BookDetailView(GenericAPIView): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer def get(self, request, pk): book = self.get_object() # get_object()方法根据pk参数查找queryset中的数据对象 serializer = self.get_serializer(book) return Response(serializer.data)
其他可以设置的属性
- pagination_class 指明分页控制类
- filter_backends 指明过滤控制后端
为了方便学习上面的GenericAPIView通用视图类,代码如下
from rest_framework.generics import GenericAPIView from app01 import models from rest_framework.response import Response from gen.serializers import Student2ModelSerializer ######GenericAPIView的接口######### class Students2View(GenericAPIView): queryset = models.Student.objects.all() # serializer_class = StudentModelSerializer def get_serializer_class(self): #self.request #-- 当前请求对象 if self.request.method == 'GET': return Student2ModelSerializer else: return StudentModelSerializer # 如果是post请求,我使用StudentModelSerializer # get请求的话: 我使用Student2ModelSerializer # 查询所有数据 def get(self,requset): serialzer_obj = self.get_serializer(instance=self.get_queryset(), many=True) return Response(serialzer_obj.data) # 添加一条记录 def post(self, request): data = request.data serialzer_obj = self.get_serializer(data=data) if serialzer_obj.is_valid(): obj = serialzer_obj.save() serialzer_obj = self.get_serializer(instance=obj) return Response(serialzer_obj.data) else: return Response({'error':'添加失败'}) class Student2View(GenericAPIView): queryset = models.Student.objects.all() serializer_class = StudentModelSerializer # 获取单条记录数据 def get(self,request, pk): # 形参名称必须叫做pk obj = self.get_object() serialzer_obj = self.get_serializer(instance=obj) return Response(serialzer_obj.data) def put(self, requset, pk): # id=pk # pk=pk 按照主键查询,
# self.get_object() 通过pk查询数据
old_obj = self.get_object() data = requset.data serialzer_obj = self.get_serializer(instance=old_obj, data=data,partial=True) if serialzer_obj.is_valid(): obj = serialzer_obj.save() serialzer_obj = self.get_serializer(instance=obj) return Response(serialzer_obj.data) else: return Response({'error':'更新失败'}) def delete(self,request,pk): self.get_object().delete() return Response('')
在使用GenericAPIView实现获取操作单个数据时,我们试图方法中的参数变量pk最好是pk名,别叫id什么的,不然还需要进行一些其他的配置,比较麻烦一些了,简单看一下源码就知道
self.get_object() 只能通过pk(id)获取单条数据,如要通过别的字段要修改queryset
序列化器类:
from rest_framework import serializers from students.models import Student class StudentModelSerializer(serializers.ModelSerializer): class Meta: model= Student fields = "__all__" # 只有两个字段的序列化器 class StudentModel2Serializer(serializers.ModelSerializer): class Meta: model= Student fields = ("name","class_null")
其实GenericAPIView只是帮我们把数据库查询啊调用序列化器类啊进行了一步封装,目的是为了将一些公共性质的代码挑出去封装一下,其他感觉没啥大用,但其实这个公共性质的代码都不要我们写了,看下面几个扩展类来增强GenericAPIView的作用。
二 、
该Mixin的list方法会对数据进行过滤和分页。
class ListModelMixin(object): """ List a queryset. """ def list(self, request, *args, **kwargs): # 过滤 queryset = self.filter_queryset(self.get_queryset()) # 分页 page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) # 序列化 serializer = self.get_serializer(queryset, many=True) return Response(serializer.data)
举例:
from rest_framework.mixins import ListModelMixin class BookListView(ListModelMixin, GenericAPIView): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer def get(self, request): return self.list(request)
如果序列化器对前端发送的数据验证失败,返回400错误。
class CreateModelMixin(object): """ Create a model instance. """ def create(self, request, *args, **kwargs): # 获取序列化器 serializer = self.get_serializer(data=request.data) # 验证 serializer.is_valid(raise_exception=True) # 保存 self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() def get_success_headers(self, data): try: return {'Location': str(data[api_settings.URL_FIELD_NAME])} except (TypeError, KeyError): return {}
示例:
def post(self,request): return self.create(requset)
如果存在,返回200, 否则返回404。
class RetrieveModelMixin(object): """ Retrieve a model instance. """ def retrieve(self, request, *args, **kwargs): # 获取对象,会检查对象的权限 instance = self.get_object() # 序列化 serializer = self.get_serializer(instance) return Response(serializer.data)
举例:
class BookDetailView(RetrieveModelMixin, GenericAPIView): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer def get(self, request, pk): return self.retrieve(request,pk)
同时也提供partial_update(request, *args, **kwargs)
方法,可以实现局部更新。
成功返回200,序列化器校验数据失败时,返回400错误。
""" Update a model instance. """ def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to # forcibly invalidate the prefetch cache on the instance. instance._prefetched_objects_cache = {} return Response(serializer.data) def perform_update(self, serializer): serializer.save() def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs)
示例:
def put(self,request,pk): """更新一条数据 ,全部字段更新 """ return self.update(request,pk)
成功返回204,不存在返回404。
class DestroyModelMixin(object): """ Destroy a model instance. """ def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) def perform_destroy(self, instance): instance.delete()
示例:
def delete(self,request,pk):
return self.destroy(request,pk)
使用GenericAPIView和视图扩展类,实现api接口,代码
from gen.serializers import StudentModelSerializer from rest_framework.views import APIView from rest_framework.generics import GenericAPIView from app01 import models from rest_framework.response import Response ######视图扩展类的接口######### from rest_framework.mixins import ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin class Students3View(GenericAPIView,ListModelMixin,CreateModelMixin): queryset = models.Student.objects.all() serializer_class = StudentModelSerializer # 查询所有数据 get-- get def get(self,requset): return self.list(requset) # 添加一条记录 def post(self, request): return self.create(request) class Student3View(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin): queryset = models.Student.objects.all() serializer_class = StudentModelSerializer # 获取单条记录数据 def get(self,request, pk): return self.retrieve(request, pk) # 更新单条记录 部分字段更新 def put(self, requset, pk): return self.partial_update(requset, pk) # 删除单条记录 def delete(self,request,pk): return self.destroy(request,pk)
下面还能对我们上面视图扩展类的代码进行简化。视图子类,也叫通用视图子类
from rest_framework.generics import ListAPIView,CreateAPIView,RetrieveAPIView, UpdateAPIView, DestroyAPIView
提供 post 方法 添加一条记录
继承自: GenericAPIView、CreateModelMixin
3.2 ListAPIView
提供 get 方法 查询所有记录
继承自:GenericAPIView、ListModelMixin
3.3 RetrieveAPIView
提供 get 方法 查询一条记录
继承自: GenericAPIView、RetrieveModelMixin
3. 4 DestoryAPIView
提供 delete 方法 删除一条记录
继承自:GenericAPIView、DestoryModelMixin
3. 5 UpdateAPIView
提供 put 和 patch 方法 put 全部字段更新 patch 部分字段更新·
提供 get、put、patch方法
继承自: GenericAPIView、RetrieveModelMixin、UpdateModelMixin
3.7 RetrieveUpdateDestoryAPIView
提供 get、put、patch、delete方法
from rest_framework.generics import ListAPIView,CreateAPIView class Students3GenericAPIView(ListAPIView,CreateAPIView): queryset = Student.objects.all() serializer_class = StudentModelSerializer from rest_framework.generics import RetrieveAPIView,UpdateAPIView,DestroyAPIView from rest_framework.generics import RetrieveUpdateDestroyAPIView # 结合了上面三个子类的功能 class Student3GenericAPIView(RetrieveUpdateDestroyAPIView): queryset = Student.objects.all() serializer_class = StudentModelSerializer
#######GenericAPIView的视图子类的接口######### from rest_framework.generics import ListAPIView,CreateAPIView,RetrieveAPIView, UpdateAPIView, DestroyAPIView class Students4View(ListAPIView,CreateAPIView): queryset = models.Student.objects.all() serializer_class = StudentModelSerializer class Student4View(RetrieveAPIView, UpdateAPIView, DestroyAPIView): queryset = models.Student.objects.all() serializer_class = StudentModelSerializer
对应的urls.py
from django.urls import path,re_path from . import views urlpatterns = [ path(r'students4/',views.Students4View.as_view()), re_path(r'students4/(?P<pk>\d+)/',views.Student4View.as_view()), ]
上述的视图 定义两个类的原因是要到查询单条数据和全部数据 ,需要定义两个get方法
使用视图集ViewSet,可以将一系列逻辑相关的动作放到一个类中:
-
-
retrieve() 提供单个数据
-
create() 创建数据
-
update() 保存数据
-
"""使用视图集把上面的两个视图类组成一个视图类""" from rest_framework.viewsets import ViewSet class StudentViewSet(ViewSet): def get_all(self,request): """获取所有学生信息""" data_list = Student.objects.all() serializer = StudentModelSerializer(instance=data_list, many=True) return Response(serializer.data) def add_student(self,request): return Response({"message":"添加成功!"}) def get_one(self,request,pk): """获取一个学生信息""" instance = Student.objects.get(pk=pk) serializer = StudentModelSerializer(instance=instance) return Response(serializer.data)
ViewSet主要通过继承ViewSetMixin来实现在调用as_view()时传入字典(如{'get':'list'})的映射处理工作。
在设置路由时,我们可以如下操作
urlpatterns = [ # 发挥下ViewSet的作用 path("students5/", views.Student2ViewSet.as_view({"get": "get_all", "post": "add_student"})), re_path("students5/(?P<pk>\d+)/", views.Student2ViewSet.as_view({"get":"get_one"})), ]
4.2 改进版 GenericViewSet
GenericViewSet就帮助我们完成了这样的继承工作,继承自GenericAPIView
与ViewSetMixin
,在实现了调用as_view()时传入字典(如{'get':'list'}
)的映射处理工作的同时,还提供了GenericAPIView
from rest_framework.viewsets import ViewSet,GenericViewSet class Students5View(GenericViewSet,ListModelMixin,CreateModelMixin,UpdateModelMixin,RetrieveModelMixin,DestroyModelMixin): queryset = models.Student.objects.all() serializer_class = StudentModelSerializer # 查询所有数据 # get -- get_all_students def get_all_students(self,request): return self.list(request) # 添加一条记录 # post -- add_student def add_student(self, request): return self.create(request) # get -- get_one_student def get_one_student(self,request, pk): return self.retrieve(request, pk) def update_one_student(self, requset, pk): return self.partial_update(requset, pk) def delete_one_student(self,request,pk): return self.destroy(request,pk)
同样 在设置路由时,我们可以如下操作,
urlpatterns = [ path('students5/', views.Students5View.as_view({'get': 'get_all_students','post': 'add_student'})), re_path('students5/(?P<pk>\d+)/', views.Students5View.as_view({'get': 'get_one_student', 'patch': 'update_one_student', 'delete': 'delete_one_student'})), ]
4.3 高级版 GenericViewSet
通过对路由的更改,直接指向视图扩展类中的封装的方法,可以更加简化
view.py
from rest_framework.viewsets import GenericViewSet class Students6View(GenericViewSet,ListModelMixin,CreateModelMixin,UpdateModelMixin,RetrieveModelMixin,DestroyModelMixin): queryset = models.Student.objects.all() serializer_class = StudentModelSerializer
视图函数为:
urlpatterns=[ path('students6/', views.Students6View.as_view({'get': 'list','post': 'create','delete': 'login'})), re_path('students6/(?P<pk>\d+)/', views.Students6View.as_view({'get': 'retrieve', 'patch': 'partial_update', 'delete': 'destroy'})), ]
4.4 最终版 ModelViewSet
view.py
from rest_framework.viewsets import ModelViewSet class Students7View(ModelViewSet): queryset = models.Student.objects.all() serializer_class = StudentModelSerializer
路由和上面一样没有变化
urlpatterns=[ path('students7/', views.Students7View.as_view({'get': 'list','post': 'create','delete': 'login'})), re_path('students7/(?P<pk>\d+)/', views.Students7View.as_view({'get': 'retrieve', 'patch': 'partial_update', 'delete': 'destroy'})), ]
from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet class StudentModelViewSet(ModelViewSet): queryset = Student.objects.all() serializer_class = StudentModelSerializer def login(self,request): #这个就可以称为自定义的action动作 """学生登录功能""" return Response({"message":"登录成功"})
url的定义
urlpatterns = [ path("students8/", views.StudentModelViewSet.as_view({"get": "list", "post": "create"})), re_path("students8/(?P<pk>\d+)/", views.StudentModelViewSet.as_view({"get": "retrieve", "put": "update", "delete": "destroy"})), path("stu/login/",views.StudentModelViewSet.as_view({"get":"login"})) ]
五 、总结
#两个基类 APIView GenericAPIView:有关数据库操作,queryset 和serializer_class #5个视图扩展类(rest_framework.mixins) CreateModelMixin:create方法创建一条 DestroyModelMixin:destory方法删除一条 ListModelMixin:list方法获取所有 RetrieveModelMixin:retrieve获取一条 UpdateModelMixin:update修改一条 #9个子类视图(rest_framework.generics) CreateAPIView:继承CreateModelMixin,GenericAPIView,有post方法,新增数据 DestroyAPIView:继承DestroyModelMixin,GenericAPIView,有delete方法,删除数据 ListAPIView:继承ListModelMixin,GenericAPIView,有get方法获取所有 UpdateAPIView:继承UpdateModelMixin,GenericAPIView,有put和patch方法,修改数据 RetrieveAPIView:继承RetrieveModelMixin,GenericAPIView,有get方法,获取一条 ListCreateAPIView:继承ListModelMixin,CreateModelMixin,GenericAPIView,有get获取所有,post方法新增 RetrieveDestroyAPIView:继承RetrieveModelMixin,DestroyModelMixin,GenericAPIView,有get方法获取一条,delete方法删除 RetrieveUpdateAPIView:继承RetrieveModelMixin,UpdateModelMixin,GenericAPIView,有get获取一条,put,patch修改 RetrieveUpdateDestroyAPIView:继承RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView,有get获取一条,put,patch修改,delete删除 #视图集 ViewSetMixin:重写了as_view ViewSet: 继承ViewSetMixin和APIView GenericViewSet:继承ViewSetMixin, generics.GenericAPIView ModelViewSet:继承mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet ReadOnlyModelViewSet:继承mixins.RetrieveModelMixin,mixins.ListModelMixin,GenericViewSet