Django REST Framework 序列化程序字段 required=false [英] Django REST Framework serializer field required=false

查看:89
本文介绍了Django REST Framework 序列化程序字段 required=false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自文档:

只读将此设置为 True 以确保在序列化表示时使用该字段,但在反序列化期间更新实例时不使用该字段.

read_only Set this to True to ensure that the field is used when serializing a representation, but is not used when updating an instance during deserialization.

默认为 False

必填通常,如果在反序列化期间未提供字段,则会引发错误.如果在反序列化期间不需要此字段,则设置为 false.

required Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization.

默认为 True.

所以我有一个模型,它有一个不可为空的字段,但我希望它被填充到 pre_save 方法中,所以我在序列化程序中将该字段设置为 required=False,但没有似乎工作.保存记录时仍然出错.

So I have a model which has a field that's not nullable but I want it to be populated in the pre_save method, so I have set the field to required=False in serializer, but doesn't seem to work. I am still getting error when saving the record.

class FavoriteListSerializer(serializers.ModelSerializer):
    owner = serializers.IntegerField(required=False)
    class Meta:
        model = models.FavoriteList

更新:我已经将 serializer_class = serializers.FavoriteListSerializer 添加到 ViewSet,现在而不是获取 This field is required,我认为它已经通过了验证,但后来我得到了 该字段不能为空. 我已经检查过 pre_save 方法没有被执行,有什么想法吗?

Update: I have added serializer_class = serializers.FavoriteListSerializer to the ViewSet, now instead of getting This field is required, which I think got past the validation but then I am getting This field cannot be null. I have checked the pre_save method is not being executed, any ideas?

推荐答案

是的,我在某个时候也遇到了这个问题.您还需要更新验证排除项.

Yeah, I ran into this issue at some point as well. You need to also update the validation exclusions.

class FavoriteListSerializer(serializers.ModelSerializer):
    owner = serializers.IntegerField(required=False)
    class Meta:
        model = models.FavoriteList

    def get_validation_exclusions(self):
        exclusions = super(FavoriteListSerializer, self).get_validation_exclusions()
        return exclusions + ['owner']

这篇关于Django REST Framework 序列化程序字段 required=false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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