ALH*_*ALH 8 python nested marshmallow data-class
在Marshmallow为了让你可以使用列表字段:
include_in = fields.List(cls_or_instance=fields.Str(),
default=['sample1', 'sample2'])
Run Code Online (Sandbox Code Playgroud)
这没问题,但我有一个新要求,即在一个领域有一个字典列表。示例有效负载:
[{
"name": "Ali",
"age": 20
},
{
"name": "Hasan",
"age": 32
}]
Run Code Online (Sandbox Code Playgroud)
This payload is part of the bigger schema, so now the question is how should I add and validate such a field?
EDIT-1:
I went a step further and could find out that there is a Dict field type in Marshmallow so until now I have the below code sample:
fields.List(fields.Dict(
keys=fields.String(validate=OneOf(('name', 'age'))),
values=fields.String(required=True)
))
Run Code Online (Sandbox Code Playgroud)
Now new problem arise and I cannot set different data types for fields in the dictionary (name and age). I'd be happy if someone could shed some light on this.
Ste*_*e L 11
如果列表中的项目具有相同的形状,则可以在 中使用嵌套字段fields.List,如下所示:
class PersonSchema(Schema):
name = fields.Str()
age = fields.Int()
class RootSchema(Schema):
people = fields.List(fields.Nested(PersonSchema))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5771 次 |
| 最近记录: |