首页 > 解决方案 > Marshmallow:根据数据动态选择Schema?

问题描述

对于 googlers 也是github 中的那个问题

我有两种类型的用户。我需要通过两种模式之一来验证用户数据。我用我的想法的代码准备了很棒的草稿,当然它不起作用。

class ExtraType0(Schema):
    nickname = fields.String()


class ExtraType1(Schema):
    id = fields.Integer()


class UserSchema(Schema):
    type = fields.String()
    extra = fields.Method(deserialize="get_extra_schema_by_user_type")

    def get_extra_schema_by_user_type(self, obj):
        if obj == 0:
            # call ExtraType0 scheme and its (de)serialization
            return fields.Nested(ExtraType0())
        else:
            # call ExtraType01scheme and its (de)serialization
            return fields.Nested(ExtraType1())

# correct data
result = UserSchema().load(
    {
        "type": 0,
        "extra": {
           "id": 0
        }
    })

# also correct data
result1 = UserSchema().load(
    {
        "type": 1,
        "extra": {
           "nickname": "user123"
        }
    })

我如何正确选择架构取决于加载的type字段数据?

标签: pythonmarshmallow

解决方案


推荐阅读