Django REST Framework serializer field required = false [英] Django REST Framework serializer field required=false

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

问题描述

从文档中:


read_only
将此值设置为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,现在而不是获得这个字段是必需的,我认为已经通过验证,但是我得到该字段不能为空。我已经检查了pre_save方法是否被执行,任何想法? / p>

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 serializer field required = false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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