简体   繁体   中英

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

I am designing a web api. I am taking request body and want some parameters to be compulsarily available or that they cannot be empty.

For eg:-

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

I want to set "id" to be required=True, and "height" also required=True.

I searched and got how to set "id" required=True {fields.Str(required=True)}, But I am not getting how to set "height" required=True.

Thanks

You have to use the nested field: https://marshmallow.readthedocs.io/en/stable/marshmallow.fields.html#marshmallow.fields.Nested

For the height parameter, you can create a serializer for processing the "detail" field with marshmallow like this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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