drf中serializer通过self.context['request']获取request对象的原因

在视图类中可通过self.request来获取request对象,是因为源码中的dispatch将其封装到类中

 def dispatch(self, request, *args, **kwargs):
        """
        `.dispatch()` is pretty much the same as Django's regular dispatch,
        but with extra hooks for startup, finalize, and exception handling.
        """
        self.args = args
        self.kwargs = kwargs
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

在获取serializer类时,源码中的get_serializer_context将其封装到类中

def get_serializer(self, *args, **kwargs):
    """
    Return the serializer instance that should be used for validating and
    deserializing input, and for serializing output.
    """
    serializer_class = self.get_serializer_class()
    kwargs.setdefault('context', self.get_serializer_context())
    return serializer_class(*args, **kwargs)

  所以,在serializer中进行校验时,可以通过self.context['request']来获取到request对象

........  

def validate_topic(self,value): if not value: # 没有话题,也可以通过 return value request = self.context('request') exists = models.Topic.objects.filter(deleted=False,id=value.id,user=request.user).exists() if not exists: raise ValidationError('话题不存在') return value

  

posted on 2022-08-10 13:08  一先生94  阅读(262)  评论(0编辑  收藏  举报

导航