【问题标题】:Nesting in Python and Marshmallow with a field that does not exist in the database使用数据库中不存在的字段嵌套在 Python 和 Marshmallow 中
【发布时间】:2021-08-18 16:39:41
【问题描述】:

我在 Marshmallow 中有这些模式:

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”属性时如何进行这种嵌套呢?

【问题讨论】:

    标签: python serialization marshmallow flask-marshmallow


    【解决方案1】:

    我想出了答案,基本上是这样的:

    parents = fields.Function(lambda x : {'mother': x.mother, 'father': x.father})
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 2023-03-17
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多