• 通用类GeneriaAPIView代码源码分析


    通用类GeneriaAPIView代码源码分析

    通用类GeneriaAPIView代码源码分析

    分析下列代码源码

    class Student2GenricAPIView(GenricAPIView):
        queryset = Student.objects.all()
        serializer_class = StudentModelSerializer
    
    def get(self,request,pk):
        instance = self.get_object() #获取queryset数据结果集中符合pk值的数据
        
        serializer = self.get_serializer(instance=instance) #序列化转换数据
        
        return Response(serializer.data) #响应数据
    

    因为GeneriaAPIView类中一共提供九种方法,就种方法包括def get_querysetdef get_object等方法

    def get_queryset(self)   #是获取所有数据
    def get_serializer_class(self)   #调整序列化器类
    def get_serializer(self,args,*kwargs)  #获取序列化器对象
    def get_object(self)   #获取一条数据
    queryset  #列表视图的查询集
    serializer_class   #视图使用的序列化器
    pagination_class  #分页器控制类
    filter_backends   #过滤控制后端
    lookup_field   #查询单一数据库对象时使用的条件字段,默认'pk'
    lookup_url_kwarg  #查询单一数据是URL中的参数关键字名称,默认与lookup_field
    

    在def get_object方法中

    验证打印结果:

    minxins扩展类

    ListModelMixin扩展类

    class ListModelMixin:
        """
        List a queryset.
        """
        def list(self, request, *args, **kwargs):
            queryset = self.filter_queryset(self.get_queryset())
    #get_queryset 获取到所有数据
            serializer = self.get_serializer(queryset, many=True)    #调用序列化器对获取到的所有queryset对象转化为字典
            return Response(serializer.data)  #返回数据
    

    CreateModelMixin扩展类

    class CreateModelMixin:
        """
        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 {}
    

    RetrieveModelMixin扩展类 Retrieve 详情

    class RetrieveModelMixin:
        """
        Retrieve a model instance.
        """
        def retrieve(self, request, *args, **kwargs):
            #get_object()  根据pk获取到一条数据赋值给instance变量
            instance = self.get_object()
            #调用序列化器对象,将数据序列化转换数据为字典
            serializer = self.get_serializer(instance)
            #响应数据
            return Response(serializer.data)
    

    UpdateModelMixin扩展类

    class UpdateModelMixin:
        """
        Update a model instance.
        """
        def update(self, request, *args, **kwargs):
            partial = kwargs.pop('partial', False)
            #通过pk查询数据
            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)
    

    DestroyModelMixin扩展类

    class DestroyModelMixin:
        """
        Destroy a model instance.
        """
        def destroy(self, request, *args, **kwargs):
            #通过pk查询数据
            instance = self.get_object()
            #调用类方法删除数据
            self.perform_destroy(instance)
            #返回状态码
            return Response(status=status.HTTP_204_NO_CONTENT)
    
    def perform_destroy(self, instance):
        instance.delete()
    

  • 相关阅读:
    springmvc单Redis实例实现分布式锁(解决锁超时问题)
    出现Please make sure you have the correct access rights and the repository exists.问题解决
    微信小程序确保获取到token值之后再执行请求
    微信小程序api封装
    微信小程序 没有找到可以构建的npm包
    vscode开发微信小程序使用less(插件Easy WXLESS)
    深入理解移动端响应式(非原创)
    git push后出现错误 ![rejected] master -> master(non-fast-forward) error:failed to push some refs to 'XXX'
    微信小程序星星评价
    更改微信小程序的组件默认样式
  • 原文地址:https://www.cnblogs.com/g15009428458/p/12354571.html
Copyright © 2020-2023  润新知