Django 只读字段的默认值

Django 只读字段的默认值,django,django-rest-framework,Django,Django Rest Framework,有一个Django Rest API项目。有一个FooSerializer,它扩展了序列化程序。ModelSerializer: class FooSerializer(serializers.ModelSerializer): foo = serializers.CharField() class Meta: model = Foo fields = DEFAULT_FOO_FIELDS + ['foo'] read_only_

有一个Django Rest API项目。有一个
FooSerializer
,它扩展了
序列化程序。ModelSerializer

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

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

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

该字段在您配置它之前不存在。因此,实现该功能的方法解析为“无”。下面是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

这是一个很好的详细回答,为我澄清了一些事情。