Django rest框架:如何在可浏览的api中显示只读字段?当我在模型序列化器中添加result = serializers.CharField(read_only=True)时,该表单不再呈现结果字段。我了解用户删除表单输入中的disabled属性的安全性问题(尽管令我惊讶的是django无法原生处理此问题),因此如何在api.html模板中从?serializers.pyclass SnippetSerializer(serializers.HyperlinkedModelSerializer):owner = serializers.ReadOnlyField(source='owner.username')result = serializers.CharField(read_only=True)class Meta: model = Snippet fields = ('title', 'code', 'owner', 'url', 'result')我是django-rest框架的新手,因此将不胜感激! (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 您有2个选择:要么计算模型中的结果或在序列化中添加字段选择什么取决于是否要在其他地方使用该计算结果以及是否可以触摸模型。当您要在模型中计算结果时请遵循以下示例的Django派生全名示例:https://github.com/django/django/blob/master/django/contrib/auth/models.py#L348或在文档中对此进行了解释:https://docs.djangoproject.com/en/dev/topics/db/models/#model-methods这将自动作为DRF的只读字段。您可以在下面的代码(get_full_name)中查看用法。当您想在序列化中添加字段时您在DRF文档中有答案:http://www.django-rest-framework.org/api-guide/fields/#serializermethodfieldSerializerMethodField这是一个只读字段...可以用于将任何类型的数据添加到对象的序列化表示中。在serializers.py中加入了示例hours_since_join:from django.contrib.auth.models import User, Groupfrom rest_framework import serializersfrom django.utils.timezone import nowclass UserSerializer(serializers.HyperlinkedModelSerializer): hours_since_joined = serializers.SerializerMethodField() class Meta: model = User fields = ('url', 'username', 'email', 'groups', 'hours_since_joined', 'first_name', 'last_name', 'get_full_name' ) def get_hours_since_joined(self, obj): return (now() - obj.date_joined).total_seconds() // 3600class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name', 'user_set')对于您的情况:class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') result = serializers.SerializerMethodField() class Meta: model = Snippet fields = ('title', 'code', 'owner', 'url', 'result') def get_result(self, obj): # code here to calculate the result # or return obj.calc_result() if you have that calculation in the model return "some result"在DRF的可浏览API中显示添加的字段您需要在Meta的字段中列出它们-参见上面的示例。这将在请求的可浏览输出中显示。但是,它不会以DRF的HTML形式显示它们。原因是HTML表单仅用于提交信息,因此restframework模板在渲染时会跳过只读字段。如您所见,全名和加入后的小时数未在表单中呈现,但可用于API:如果要在表单上显示只读字段您需要覆盖restframework模板。确保您的模板在restframework之前加载(即您的应用在settings.py中的restframework上方)使用应用程序下的模板目录在模板目录中创建子目录:restframework / horizo​​ntal从Python的Lib \ site-packages \ rest_framework \ templates \ rest_framework \ horizo​​ntal \复制form.html和input.html更改form.html{% load rest_framework %}{% for field in form %} {% render_field field style=style %}{% endfor %}更改input.html中的输入行(添加禁用的属性)<input name="{{ field.name }}" {% if field.read_only %}disabled{% endif %} {% if style.input_type != "file" %}class="form-control"{% endif %} type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}>结果: (adsbygoogle = window.adsbygoogle || []).push({});
10-07 13:30