Django Rest框架Nested Serializer required = False error [英] Django Rest Framework Nested Serializer required=False error

查看:440
本文介绍了Django Rest框架Nested Serializer required = False error的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在DRF v3.1中,我有一个嵌套的序列化器,很像文档中详细描述的序列号 - http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects

  class SerializerA(serializers.Serializer):
details = DetailsS​​erializer(required = False)
但是,当尝试使用此序列化程序并且不提供详细信息时,我收到以下内容:

  {u'details':[你的字段可能不为空。]] 

鉴于文档,这看起来不正确?



有其他人遇到这个或可以将其验证为错误?

解决方案

好的,所以Kevin Browns的评论是正确的。我需要添加allow_null = True。

  class SerializerA(serializers.Serializer):
details = DetailsS​​erializer(required = False,allow_null = True)

这样做的原因是,require = False允许字段详细信息在构建序列化程序时不要从数据中删除。



eg
s = SerializerA(data = {})



而allow_null允许指定参数但是为空。



例如
s = SerializerA(data = {'details':None})



问题与DRF Browsable API,但我会问另一个问题。


In DRF v3.1, I have a nested serializer much like the one detailed in the docs - http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects

class SerializerA(serializers.Serializer):
    details = DetailsSerializer(required=False)

However, when trying to use this serializer and not supplying the details, I receive the following:

{u'details': [u'This field may not be null.']}

This seems incorrect given the docs?

Has anyone else come across this or can verify this as a bug?

解决方案

Ok, so Kevin Browns comment is correct. I needed to add allow_null=True.

class SerializerA(serializers.Serializer):
    details = DetailsSerializer(required=False, allow_null=True)

The reason for this is that having required=False allows the field details to be absent from the data when constructing the serializer.

e.g. s = SerializerA(data={})

whereas allow_null permits the the param to be specified but be null.

e.g. s = SerializerA(data={'details': None})

This opens up another issue with DRF Browsable API, but i'll ask that in a different question.

这篇关于Django Rest框架Nested Serializer required = False error的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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