【问题标题】:How should I add a field containing a list of dictionaries in Marshmallow Python?我应该如何在 Marshmallow Python 中添加一个包含字典列表的字段?
【发布时间】:2019-07-10 08:08:50
【问题描述】:

Marshmallow 中有一个可以使用的列表字段:

include_in = fields.List(cls_or_instance=fields.Str(),
                         default=['sample1', 'sample2'])

这没关系,但我有一个新要求,即在字段中包含字典列表。一个样本载荷:

[{
  "name": "Ali",
  "age": 20
},
{
  "name": "Hasan",
  "age": 32
}]

此有效负载是更大架构的一部分,所以现在的问题是我应该如何添加和验证这样的字段?


EDIT-1: 我更进一步,可以发现Marshmallow 中有一个Dict 字段类型,所以到目前为止我有以下代码示例:

fields.List(fields.Dict(
        keys=fields.String(validate=OneOf(('name', 'age'))),
        values=fields.String(required=True)
))

现在出现了新问题,我无法为字典中的字段设置不同的数据类型(nameage)。如果有人能对此有所了解,我会很高兴。

【问题讨论】:

标签: python nested marshmallow data-class


【解决方案1】:

如果列表中的项目具有相同的形状,您可以在fields.List 中使用嵌套字段,如下所示:

class PersonSchema(Schema):
    name = fields.Str()
    age = fields.Int()

class RootSchema(Schema):
    people = fields.List(fields.Nested(PersonSchema))

【讨论】:

    【解决方案2】:

    另一种使用一个模式类验证字段中字典列表的方法。

    from marshmallow import Schema, ValidationError
    
    
    class PeopleSchema(Schema):
        name = fields.Str(required=True)
        age = fields.Int(required=True)
    
    
    people = [{
        "name": "Ali",
        "age": 20
    },
    {
        "name": "Hasan",
        "age": 32
    },
    {
        "name": "Ali",
        "age": "twenty"  # Error: Not an int
    }
    ]
    
    
    def validate_people():
        try:
            validated_data = PeopleSchema(many=True).load(people)
        except ValidationError as err:
            print(err.messages)
    
    validate_people()
    

    输出:

    {2: {'age': ['Not a valid integer.']}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 2021-11-03
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      相关资源
      最近更新 更多