在视图基类文章中的 5 个接口虽然可以继承 GenericAPIView 基类,但执行的代码还是繁琐。可以使用几种后端视图(对数据资源进行曾删改查)处理流程的实现,减少代码的编写量
注意点:这五个扩展类需要搭配GenericAPIView父类,因为五个扩展类的实现需要调用GenericAPIView提供的序列化器与数据库查询的方法。
导入语句:
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from rest_framework.mixins import UpdateModelMixin, DestroyModelMixin, RetrieveModelMixin
列表视图扩展类,提供list(request, *args, **kwargs)
方法快速实现列表视图,返回200状态码。使用该方法可以代替接口中查询所有的功能代码
使用 ListModelMixin 实现查询所有(部分代码)
from rest_framework.generics import GenericAPIView
from app01 import models
from app01.serializer import BookSerializer
from rest_framework.mixins import ListModelMixin, CreateModelMixin
class BookView(GenericAPIView, ListModelMixin):
queryset = models.Book.objects
serializer_class = BookSerializer
def get(self, request):
# 执行父类也就是 ListModelMixin 中的 list 方法
return super().list(request)
查看源码
class ListModelMixin:
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)
创建视图扩展类,提供create(request, *args, **kwargs)
方法快速实现创建资源的视图,成功返回201状态码。如果序列化器对前端发送的数据验证失败,返回 400 错误
使用 CreateModelMixin 实现创建(部分代码)
from rest_framework.generics import GenericAPIView
from app01 import models
from app01.serializer import BookSerializer
from rest_framework.mixins import CreateModelMixin
class BookView(GenericAPIView, CreateModelMixin):
queryset = models.Book.objects
serializer_class = BookSerializer
def post(self, request):
return super().create(request)
查看源码
class CreateModelMixin(object):
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 {}
该拓展类可以用于查询单个对象时使用,使用方法retrieve(request, *args, **kwargs)
。如果查询的对象不存在则返回404。
需要注意的是,查询单个、删除单个、修改单个接口由于需要查找到指定对象,因此需要传入查询参数,例如 pk。
使用 RetrieveModelMixin 实现查询单个(部分代码)
from rest_framework.generics import GenericAPIView
from app01 import models
from app01.serializer import BookSerializer
from rest_framework.mixins import RetrieveModelMixin
class BookView1(GenericAPIView, RetrieveModelMixin):
queryset = models.Book.objects
serializer_class = BookSerializer
def get(self, request, **kwargs):
return super().retrieve(request, **kwargs)
查看源码
class RetrieveModelMixin(object):
def retrieve(self, request, *args, **kwargs):
# 获取对象,会检查对象的权限
instance = self.get_object()
# 序列化
serializer = self.get_serializer(instance)
return Response(serializer.data)
更新视图扩展类,提供update(request, *args, **kwargs)
方法,可以快速实现更新一个存在的数据对象。成功返回200,序列化器校验数据失败时,返回400错误
使用 UpdateModelMixin 实现修改单个(部分代码)
from rest_framework.generics import GenericAPIView
from app01 import models
from app01.serializer import BookSerializer
from rest_framework.mixins import UpdateModelMixin
class BookView1(GenericAPIView, UpdateModelMixin):
queryset = models.Book.objects
serializer_class = BookSerializer
def put(self, request, **kwargs):
return super().update(request, **kwargs)
查看源码
class UpdateModelMixin:
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):
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)
其实update
方法提供的是全局修改,而partial_update(request, *args, **kwargs)
方法可以实现局部更新,但并不常用。
删除视图扩展类,提供destroy(request, *args, **kwargs)
方法,用于实现删除一个存在的数据对象。成功返回204,不存在返回404。
使用 DestroyModelMixin 实现删除单个(部分代码)
from rest_framework.generics import GenericAPIView
from app01 import models
from app01.serializer import BookSerializer
from rest_framework.mixins import DestroyModelMixin
class BookView1(GenericAPIView, DestroyModelMixin):
queryset = models.Book.objects
serializer_class = BookSerializer
def delete(self, request, **kwargs):
return super().destroy(request, **kwargs)
查看源码
class DestroyModelMixin:
"""
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()