Django的休息框架 - 如何添加在ModelSerializer自定义字段 [英] Django Rest Framework - How to add custom field in ModelSerializer

查看:472
本文介绍了Django的休息框架 - 如何添加在ModelSerializer自定义字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 ModelSerializer 并要添加自定义字段,不是我的模型的一部分​​。

I created a ModelSerializer and want to add a custom field which is not part of my model.

我发现了一个说明,以增加额外的字段<一个href=\"http://django-rest-framework.org/api-guide/serializers.html#specifying-fields-explicitly\">here我试过如下:

I found a description to add extra fields here and I tried the following:

customField = CharField(source='my_field')

当我加入这个领域,并打电话给我的的validate()函数,那么这个字段是不能的一部分 ATTR 字典。 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? Thanks alot!

推荐答案

您正在做正确的事情,但 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的休息框架 - 如何添加在ModelSerializer自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆