read_only_fields的默认值

时间:2017-07-31 05:42:57

标签: django django-rest-framework

有一个Django Rest API项目。有FooSerializer扩展serializers.ModelSerializer

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

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

每次都必须将read_only_fields设置为空列表,或者空列表是否为默认值,表达式是否可以忽略?

1 个答案:

答案 0 :(得分: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