在 Python 和 Marshmallow 中嵌套数据库中不存在的字段

2023-12-21

我在棉花糖中有这些模式:

class Parents(Schema):
     father = fields.String(data_key="father")
     mother = fields.String(data_key="mother")

class UserSchema(Schema):
     user_id = fields.Integer(data_key="userID")
     name = fields.String(data_key="nameUser")
     parents = Nested(Parents, many=True)

“father”和“mother”与“user_id”和“name”在同一个表中,但“parents”只是 JSON 的一个属性:

{
    "data": [
        {
            "userID": 1,
            "nameUser": "Guido",
            "parents": {
                "father": "John",
                "mother": "Marie"
            }
        }
        ...
    ]
}

我尝试使用“嵌套”类,但它不起作用。那么当模型中不存在“parents”属性时如何进行嵌套呢?


我找到了答案,基本上是这样的:

parents = fields.Function(lambda x : {'mother': x.mother, 'father': x.father})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Python 和 Marshmallow 中嵌套数据库中不存在的字段 的相关文章

随机推荐