2017-07-31 8 views
0

Django Rest APIプロジェクトがあります。 serializers.ModelSerializerを拡張FooSerializerがあります:read_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