• restful 在接口中获取 request.user


     结论:在serializer中可以调用request

    有下面的接口

    class TestSer(serializers.ModelSerializer):
        xx = serializers.SerializerMethodField()         自定义的字段
    
        class Meta:
            model = models.Topic
            fields = '__all__'
    
        def get_xx(self,obj):                    写什么就显示什么
            return 124
     
    class Test(ListAPIView):
        queryset = models.Topic.objects
        serializer_class = TestSer

    问题是 在 get_xx 中如何获取 request

        def get_xx(self,obj):
            # 获取 request
            self.context['request']
            return 124

    解析

    用户进来走的是

    class Test(ListAPIView):
        queryset = models.Topic.objects
        serializer_class = TestSer

    要执行一个   GET 的 方法 本身没有去找父类  ListAPIView

    class ListAPIView(mixins.ListModelMixin,
                      GenericAPIView):
        """
        Concrete view for listing a queryset.
        """
        def get(self, request, *args, **kwargs):
            return self.list(request, *args, **kwargs)

    父类ListAPIView的get方法 返回一个list 自己的也没有, 父类ListAPIView也没有 在继续找上门的父类  ListModelMixin

    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)

    分析上面的代码看到

    # 执行get_queryset也是先去自己的类找没有 父类ListAPIView没有在找ListModelMixin也没有
    queryset = self.filter_queryset(self.get_queryset())

    现在去   GenericAPIView  这个类有点长 

    我们可以看到有  get_queryset 的方法  进去  我把注释写到里面  标好了步骤

    class GenericAPIView(views.APIView):
        """
        Base class for all other generic views.
        """
        # You'll need to either set these attributes,
        # or override `get_queryset()`/`get_serializer_class()`.
        # If you are overriding a view method, it is important that you call
        # `get_queryset()` instead of accessing the `queryset` property directly,
        # as `queryset` will get evaluated only once, and those results are cached
        # for all subsequent requests.
        queryset = None
        serializer_class = None
    
        # If you want to use object lookups other than pk, set 'lookup_field'.
        # For more complex lookup requirements override `get_object()`.
        lookup_field = 'pk'
        lookup_url_kwarg = None
    
        # The filter backend classes to use for queryset filtering
        filter_backends = api_settings.DEFAULT_FILTER_BACKENDS
    
        # The style to use for queryset pagination.
        pagination_class = api_settings.DEFAULT_PAGINATION_CLASS
    
        def get_queryset(self):
            """
            Get the list of items for this view.
            This must be an iterable, and may be a queryset.
            Defaults to using `self.queryset`.
    
            This method should always be used rather than accessing `self.queryset`
            directly, as `self.queryset` gets evaluated only once, and those results
            are cached for all subsequent requests.
    
            You may want to override this if you need to provide different
            querysets depending on the incoming request.
    
            (Eg. return a list of items that is specific to the user)
            """
            assert self.queryset is not None, (
                "'%s' should either include a `queryset` attribute, "
                "or override the `get_queryset()` method."
                % self.__class__.__name__
            )
         # 第一步      # 这个调用的self.qyeryset 也是先去自己的里面找 这次我们有,他有一个判断 我们自己写的语句不加all的时候他给我们加
         # 我们写的是 queryset = models.Topic.objects
         # 在回到 ListMoselMixin 分页我们先不看
    serializer = self.get_serializer(queryset, many=True
    
            queryset = self.queryset
            if isinstance(queryset, QuerySet):
                # Ensure queryset is re-evaluated on each request.
                queryset = queryset.all()
            return queryset
    
        def get_object(self):
            """
            Returns the object the view is displaying.
    
            You may want to override this if you need to provide non-standard
            queryset lookups.  Eg if objects are referenced using multiple
            keyword arguments in the url conf.
            """
            queryset = self.filter_queryset(self.get_queryset())
    
            # Perform the lookup filtering.
            lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
    
            assert lookup_url_kwarg in self.kwargs, (
                'Expected view %s to be called with a URL keyword argument '
                'named "%s". Fix your URL conf, or set the `.lookup_field` '
                'attribute on the view correctly.' %
                (self.__class__.__name__, lookup_url_kwarg)
            )
    
            filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
            obj = get_object_or_404(queryset, **filter_kwargs)
    
            # May raise a permission denied
            self.check_object_permissions(self.request, obj)
    
            return obj
      # 第二步

    def get_serializer(self, *args, **kwargs): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """
          # 走的是get_serializer_class serializer_class = self.get_serializer_class()
          # 在这里添加了一些东西 在去看下面的这个函数去干了什么 kwargs[
    'context'] = self.get_serializer_context()
          # 咱们自己写的实例化的类加括号 实例化 还传一个kwargs 里面有一个context跳回上一行的注释
    return serializer_class(*args, **kwargs) def get_serializer_class(self): """ Return the class to use for the serializer. Defaults to using `self.serializer_class`. You may want to override this if you need to provide different serializations depending on the incoming request. (Eg. admins get full serialization, others get basic serialization) """ assert self.serializer_class is not None, ( "'%s' should either include a `serializer_class` attribute, " "or override the `get_serializer_class()` method." % self.__class__.__name__ )       # 就是返回 我们自己写的 serializer_class = TestSER 在回到上面 return self.serializer_class def get_serializer_context(self): """ Extra context provided to the serializer class. """
        # 添加了下面的这些东西
        return
    { 'request': self.request,
            # url传过来的参数
    'format': self.format_kwarg, 'view': self } .......后面没有啥用的源码 我就删掉啦

    好了 其他的都不需要看了

    自己写的  所以 self.context['request'] 就有登陆的人的值
    class
    TestSer(serializers.ModelSerializer): xx = serializers.SerializerMethodField() class Meta: model = models.Topic fields = '__all__' def get_xx(self,obj): # 获取 request self.context['request'] return 124
  • 相关阅读:
    surging+EFCore 服务实现入门
    surging+CentOS7+docker+rancher2.0 入门部署教程
    Aspnet Zero中使用Windows service (Topshelf)来承载Quartz.net任务
    解决 EntityFrameworkCore tool 3.1 init.ps1 is not recognized 问题
    基于Bitnami gitlab OVA包的gitlab 环境搭建
    基于ng-zorro的ASP.NET ZERO前端实现
    图像滑动窗口分割
    论文答辩准备
    transgan_pytorch
    Pytorch常用代码整理
  • 原文地址:https://www.cnblogs.com/a438842265/p/12498665.html
Copyright © 2020-2023  润新知