繁体   English   中英

如何为 python django 中的 json 的参数设置 required = True?

[英]How to set required = True for an parameter of json in python django?

我正在设计一个 web api。 我正在接受请求正文并希望某些参数强制可用或它们不能为空。

例如:-

request body = 
{
"user" : username,
""id" : ID,
"detail" : {
    "hair" : yes,
    "height" : 111,
    "weight" : 29
    }
}

我想将“id”设置为required=True,并且“height”也需要=True。

我搜索并得到了如何设置“id” required=True {fields.Str(required=True)},但我没有得到如何设置“height” required=True。

谢谢

您必须使用嵌套字段: https://marshmallow.readthedocs.io/en/stable/marshmallow.fields.html#marshmallow.fields.Nested

对于高度参数,您可以创建一个序列化程序来处理带有棉花糖的“详细信息”字段,如下所示:

from rest_marshmallow import fields, Schema

class DetailSchema(Schema):
    hair = fields.String()
    width = fields.Integer()
    height = fields.Integer(required=True)

class RequestSchema(Schema):
    user = fields.String()
    id = fields.Integer(required=True)
    artist = fields.Nested(DetailSchema)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM