这里呢,我将为大家介绍一下DRF框架,为我们提供的试图扩展类的使用方法即作用。
在使用视图扩展类时,需要将mixins模块导入到view文件中。
from rest_framework import mixins
并且,在使用视图扩展类时,必须结合GenericAPIView基类一起使用。
所谓,视图的扩展类,就是GenericAPIView的子类,他们继承自GenericAPIView类,并在此基础上封装了增删改查的功能函数。
模板代码:
class BookInfoAPIView(mixins.视图扩展类, GenericAPIView): '''使用视图扩展类定义API''' # 1. 设置查询集 queryset = BookInfo.objects.all() # 2. 设置序列化器 serializer_class = BookInfoModelSerializer # 请求方法
1. ListModelMixin扩展类
ListModelMixin扩展类,为我们提供了一个list方法,实现了查询所有信息的功能,并返回JSON数据。
源代码:
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)
案例代码:
这里的需求是,查询出所有图书信息。
class BookInfoAPIView(mixins.ListModelMixin, GenericAPIView): '''使用视图扩展类定义API''' # 1. 设置查询集 queryset = BookInfo.objects.all() # 2. 设置序列化器 serializer_class = BookInfoModelSerializer def get(self, request): return self.list(request)
2. CreateModelMixin扩展类
CreateModelMixin扩展类,为我们提供了一个create方法,实现了添加数据的功能,并返回JSON数据。
源代码:
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 {}
案例代码:
class BookInfoAPIView(mixins.CreateModelMixin, GenericAPIView): '''使用视图扩展类定义API 实现添加图书信息 ''' # 1. 设置查询集 queryset = BookInfo.objects.all() # 2. 设置序列化器 serializer_class = BookInfoModelSerializer def post(self, request): return self.create(request)
3. RetrieveModelMixin扩展类
RetrieveModelMixin扩展类,为我们提供了一个retrieve方法,实现了查询指定数据信息的功能,并响应JSON数据。
源代码:
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 BookInfoPkView(mixins.RetrieveModelMixin, GenericAPIView): '''查询指定模型数据''' # 1. 设置查询集 queryset = BookInfo.objects.all() # 2. 设置序列化器 serializer_class = BookInfoModelSerializer def get(self, request, pk): return self.retrieve(request)
4. UpdateModelMixin扩展类
UpdateModelMixin扩展类,为我们封装了update方法,实现了更新数据的功能并返回JSON数据。
源代码:
class UpdateModelMixin(object): """ 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)
案例代码:
class BookInfoPkView(mixins.UpdateModelMixin, GenericAPIView): '''修改指定模型数据''' # 1. 设置查询集 queryset = BookInfo.objects.all() # 2. 设置序列化器 serializer_class = BookInfoModelSerializer def put(self, request, pk): return self.update(request)
5. DestroyModelMixin扩展类
DestroyModelMixin扩展类,为我们提供了destroy方法,实现了删除数据的功能并返回JSON数据。
源代码:
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()
案例代码:
class BookInfoPkView(mixins.DestroyModelMixin, GenericAPIView): '''查询、修改指定模型数据''' # 1. 设置查询集 queryset = BookInfo.objects.all() # 2. 设置序列化器 serializer_class = BookInfoModelSerializer def delete(self, request, pk): return self.destroy(request)
以上,便是视图扩展类的简介。