You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Django中为JSON参数(含嵌套参数)设置required=True?

如何为Web API请求体中的嵌套字段设置必填项

从你给出的请求体结构和使用fields.Str(required=True)的方式来看,你应该是在用Marshmallow这类Schema校验库。针对嵌套字段的必填设置,核心是先给嵌套对象单独定义子Schema,再在主Schema中引用它,具体步骤如下:

  1. 定义嵌套对象的子Schema
    先为detail这个嵌套对象创建一个独立的Schema,在里面把height设置为必填项:

    from marshmallow import Schema, fields
    
    class DetailSchema(Schema):
        hair = fields.Str()  # 非必填字段,按需设置类型
        height = fields.Integer(required=True)  # 明确设置height为必填
        weight = fields.Integer()  # 非必填字段,按需设置类型
    
  2. 在主Schema中引用子Schema
    接着在顶层的请求体Schema里,用fields.Nested()引用刚才定义的DetailSchema,同时保留id的必填设置:

    class RequestBodySchema(Schema):
        user = fields.Str()
        id = fields.Str(required=True)  # 顶层id字段必填
        detail = fields.Nested(DetailSchema)  # 引用子Schema,自动校验嵌套字段规则
    
  3. 可选:强制要求detail对象本身必须存在
    如果你的业务逻辑里detail这个对象也必须出现在请求体中(不能缺失),可以给detail字段也加上required=True:

    detail = fields.Nested(DetailSchema, required=True)
    

这样设置后,校验请求体时会自动检查:

  • 顶层的id必须存在且不为空
  • 嵌套在detail里的height必须存在且为合法的整数

内容的提问来源于stack exchange,提问作者Digvijay Nikam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 05:45:41