Django Rest Framework - 如何在ModelSerializer中添加自定义字段 [英] Django Rest Framework - How to add custom field in ModelSerializer
问题描述
我创建了一个 ModelSerializer
,并希望添加一个不属于我的模型的自定义字段。
I created a ModelSerializer
and want to add a custom field which is not part of my model.
我找到一个描述来添加额外的字段这里,我尝试了以下:
I found a description to add extra fields here and I tried the following:
customField = CharField(source='my_field')
当我添加此字段并调用我的 validate()
函数时,此字段不是 attr
dict。 attr
包含除额外字段外的所有模型字段。所以我无法访问我的覆盖验证中的这个字段,可以吗?
When I add this field and call my validate()
function then this field is not part of the attr
dict. attr
contains all model fields specified except the extra fields. So I cannot access this field in my overwritten validation, can I?
当我将这个字段添加到字段列表中,如下所示:
When I add this field to the field list like this:
class Meta:
model = Account
fields = ('myfield1', 'myfield2', 'customField')
然后我收到一个错误,因为 customField
不是我的模型的一部分 - 什么是正确的,因为我想为这个序列化程序添加它。
then I get an error because customField
is not part of my model - what is correct because I want to add it just for this serializer.
有没有办法添加自定义字段?
Is there any way to add a custom field?
推荐答案
您正在做正确的事情,除了 CharField
(和其他类型的字段)用于可写字段。
You're doing the right thing, except that CharField
(and the other typed fields) are for writable fields.
在这种情况下,您只需要一个简单的只读字段,因此只需使用:
In this case you just want a simple read-only field, so instead just use:
customField = Field(source='get_absolute_url')
这篇关于Django Rest Framework - 如何在ModelSerializer中添加自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!