Django REST Framework 序列化程序字段 required=false

编程入门 行业动态 更新时间:2024-10-26 20:32:53
本文介绍了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

本文发布于:2023-10-10 01:17:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1477290.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   序列化   程序   REST   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!