您有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/#serializermethodfield
SerializerMethodField 这是一个只读字段…可用于将任何类型的数据添加到对象的序列化表示中。
在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', 'pre', 'owner', 'url', 'result') def get_result(self, obj): # pre 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 / horizontal
从Python的Lib site-packages rest_framework templates rest_framework horizontal 复制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" %}{% endif %} type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}>
结果:



