基于Mixin扩展类和GenericAPIView实现接口
基于Mixin扩展类和GenericAPIView实现接口
10.1 扩展类简介
(1)ListModelMixin
列表视图扩展类,提供list(request, *args, **kwargs)
方法快速实现列表视图,返回200状态码。
该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)
(2)CreateModelMixin
创建视图扩展类,提供create(request, *args, **kwargs)
方法快速实现创建资源的视图,成功返回201状态码。
如果序列化器对前端发送的数据验证失败,返回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 {}
(3) RetrieveModelMixin
详情视图扩展类,提供retrieve(request, *args, **kwargs)
方法,可以快速实现返回一个存在的数据对象。
如果存在,返回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)
(4)UpdateModelMixin
更新视图扩展类,提供update(request, *args, **kwargs)
方法,可以快速实现更新一个存在的数据对象。
同时也提供partial_update(request, *args, **kwargs)
方法,可以实现局部更新。
成功返回200,序列化器校验数据失败时,返回400错误。
源代码:
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)
(5)DestroyModelMixin
删除视图扩展类,提供destroy(request, *args, **kwargs)
方法,可以快速实现删除一个存在的数据对象。
成功返回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()
10.2 快速实现五个接口
视图
"""
使用drf内置的模型扩展类(混入类)结合GenericAPIView快速实现五个接口
from rest_framework.mixins import ListModelMixin 获取多条数据,返回响应结果
from rest_framework.mixins import CreateModelMixin 添加一条数据,返回结果
from rest_framework.mixins import RetrieveModelMixin 获取一条数据,返回结果
from rest_framework.mixins import UpdateModdelMixin 更新一条数据返回结果
from rest_framework.mixins import DestroyModelMixin 删除一条数据,返回结果
"""
from app.models import studentsInfo
from .serializers import StudentModelSerializer
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
DestroyModelMixin
class StudentGenericAPIViewMixin(GenericAPIView, ListModelMixin, CreateModelMixin):
queryset = studentsInfo.objects.all()
serializer_class = StudentModelSerializer
def get(self, request):
"""获取多条数据"""
return self.list(request)
def post(self, request):
"""添加一条数据"""
return self.create(request)
class StudentGenericAPIViewMixin2(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
queryset = studentsInfo.objects.all()
serializer_class = StudentModelSerializer
def get(self, request, pk):
"""获取一条数据"""
return self.retrieve(request, pk=pk)
def put(self, request, pk):
"""更新一条数据"""
return self.update(request, pk=pk)
def delete(self, request, pk):
"""删除一条数据"""
return self.destroy(request, pk=pk)
路由
from django.urls import path, re_path
from . import views
urlpatterns = [
# APIView
path('students/', views.StudentView.as_view()),
re_path(r'^students/(?P<pk>\d+)/$', views.StudentAPIView.as_view()),
# GenericAPIView
path('students2/', views.StudentGenericAPIView.as_view()),
re_path(r'^students2/(?P<pk>\d+)/$', views.StudentGenericAPIView2.as_view()),
# GenericAPIView和mixin
path('students3/', views.StudentGenericAPIViewMixin.as_view()),
re_path(r'^students3/(?P<pk>\d+)/$', views.StudentGenericAPIViewMixin2.as_view())