首页 > 其他分享 >drf之视图扩展类(混入类)

drf之视图扩展类(混入类)

时间:2023-02-03 20:22:40浏览次数:43  
标签:混入 get self request 视图 kwargs serializer drf

### 1.2.2 5个视图扩展类 - 也叫混入类。

作用:
提供了几种后端视图(对数据资源进行增删改查)处理流程的实现,如果需要编写的视图属于这五种,则视图可以通过继承相应的扩展类来复用代码,减少自己编写的代码量。
这五个扩展类需要搭配GenericAPIView通用视图基类,因为五个扩展类的实现需要调用GenericAPIView提供的序列化器与数据库查询的方法。

 

#### 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)
 

举例:

 
from rest_framework.mixins import ListModelMixin,CreateModelMixin
class StudentMixinAPIView(GenericAPIView,ListModelMixin,CreateModelMixin):
    serializer_class = StudentModelSerializer
    queryset = Student.objects
    def get(self,request,*args,**kwargs):
        """获取所有模型信息"""
        return self.list(request,*args,**kwargs)
 

#### 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 {}
 

视图代码

 
from rest_framework.mixins import ListModelMixin,CreateModelMixin
class StudentMixinAPIView(GenericAPIView,ListModelMixin,CreateModelMixin):
    serializer_class = StudentModelSerializer
    queryset = Student.objects
    def get(self,request,*args,**kwargs):
        """获取所有模型信息"""
        return self.list(request,*args,**kwargs)

    def post(self,request):
        """添加一个模型信息"""
        return self.create(request)
 

#### 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)
 

视图代码:

 
from rest_framework.mixins import RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
class Student1MixinAPIView(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):
    serializer_class = StudentModelSerializer
    queryset = Student.objects
    def get(self,request,pk):
        """获取一个模型信息"""
        return self.retrieve(request,pk)
 

#### 4)UpdateModelMixin

标签:混入,get,self,request,视图,kwargs,serializer,drf
From: https://www.cnblogs.com/TodayWind/p/17090348.html

相关文章