drf serializer获取viewset 中的上下文context,自定义上下文详解编程语言

  1. 在视图继承ViewAPI时,在初始化序列化类时可以传递context参数

  2. 在视图继承viewset后,我们只能对序列化类做一个声明,但是在实际创建序列化实例时,会帮我们将rquest参数传递到实列中,可以使用self.context来获取.

源码分析:

BaseSerializer中:

class BaseSerializer(Field): 
    """ 
    The BaseSerializer class provides a minimal class which may be used 
    for writing custom serializer implementations. 
 
    Note that we strongly restrict the ordering of operations/properties 
    that may be used on the serializer in order to enforce correct usage. 
 
    In particular, if a `data=` argument is passed then: 
 
    .is_valid() - Available. 
    .initial_data - Available. 
    .validated_data - Only available after calling `is_valid()` 
    .errors - Only available after calling `is_valid()` 
    .data - Only available after calling `is_valid()` 
 
    If a `data=` argument is not passed then: 
 
    .is_valid() - Not available. 
    .initial_data - Not available. 
    .validated_data - Not available. 
    .errors - Not available. 
    .data - Available. 
    """ 
 
    def __init__(self, instance=None, data=empty, **kwargs): 
        self.instance = instance 
        if data is not empty: 
            self.initial_data = data 
        self.partial = kwargs.pop('partial', False) 
        self._context = kwargs.pop('context', {}) # 传递上下文参数 
        kwargs.pop('many', None) 
        super(BaseSerializer, self).__init__(**kwargs) 

在viewset中是怎样自动传递上下文的的:

class GenericAPIView(views.APIView): 
    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['context'] = self.get_serializer_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__ 
        ) 
 
        return self.serializer_class 
      #这里设置了上下文 
    def get_serializer_context(self): 
        """ 
        Extra context provided to the serializer class. 
        """ 
        return { 
            'request': self.request, 
            'format': self.format_kwarg, 
            'view': self 
        } 

所以如果要自定以上下文的的值,可以重写get_serializer_context方法.

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/18444.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论