2017-07-31 34 views
0

有一個Django Rest API項目。有延伸serializers.ModelSerializer一個FooSerializerread_only_fields的默認值

class FooSerializer(serializers.ModelSerializer): 
    foo = serializers.CharField() 

    class Meta: 
     model = Foo 
     fields = DEFAULT_FOO_FIELDS + ['foo'] 
     read_only_fields = [] 

是否read_only_fields具有每一次或空單設置空列表是默認值和表達式可以不理?

回答

1

該字段在配置之前不存在。因此,實現該功能的方法將解析爲None。下面是ModelSerializer類中的一個方法的實現,負責提取元信息:

def get_extra_kwargs(self): 
     """ 
     Return a dictionary mapping field names to a dictionary of 
     additional keyword arguments. 
     """ 
     extra_kwargs = copy.deepcopy(getattr(self.Meta, 'extra_kwargs', {})) 

     read_only_fields = getattr(self.Meta, 'read_only_fields', None) 
     if read_only_fields is not None: 
      if not isinstance(read_only_fields, (list, tuple)): 
       raise TypeError(
        'The `read_only_fields` option must be a list or tuple. ' 
        'Got %s.' % type(read_only_fields).__name__ 
       ) 
      for field_name in read_only_fields: 
       kwargs = extra_kwargs.get(field_name, {}) 
       kwargs['read_only'] = True 
       extra_kwargs[field_name] = kwargs 

     else: 
      # Guard against the possible misspelling `readonly_fields` (used 
      # by the Django admin and others). 
      assert not hasattr(self.Meta, 'readonly_fields'), (
       'Serializer `%s.%s` has field `readonly_fields`; ' 
       'the correct spelling for the option is `read_only_fields`.' % 
       (self.__class__.__module__, self.__class__.__name__) 
      ) 

     return extra_kwargs 
+0

這是一個很好的詳細答案,爲我澄清了一些事情。 – Oleg