如何在 Marshmallow 中人为地嵌套模式?

How can I artificially nest schemas in Marshmallow?

在 Marshmallow 中,有没有办法将当前对象传递给 Nested 字段以生成人为嵌套的序列化?例如,考虑我正在序列化的这个对象:

example = Example(
    name="Foo",
    address="301 Elm Street",
    city="Kalamazoo",
    state="MI",
)

我想为此生成 JSON,如下所示:

{
    "name": "Foo",
    "address": {
            "street": "301 Elm Street",
            "city": "Kalamazoo",
            "state": "MI"
    }
}

本质上,这将是 ExampleSchema 中的嵌套 AddressSchema,类似这样:

class AddressSchema:
    street = fields.String(attribute="address")
    city = fields.String()
    state = fields.String()

class ExampleSchema:
    name = fields.String()
    address = fields.Nested(AddressSchema)

...但这并不是我想要的。我可以使用自定义函数,但如果可能,我想使用内置方法。

我设法找到了一个解决方案,使我能够保留内省并仅使用内置字段;不过,这有点奇怪。我修改了 ExampleSchema 以包含一个 @pre_dump 挂钩,它添加了一个自引用属性,并将该字段指向该字段:

class ExampleSchema:
    name = fields.String()
    address = fields.Nested(
        AddressSchema, attribute="_marshmallow_self_reference"
    )

    @pre_dump
    def add_self_reference(self, data):
        setattr(data, "_marshmallow_self_reference", data)

您可以如下定义地址字段

address = fields.Function(lambda x: {'street': x.street, 'city': x.city, 'state': x.state})

归功于此 post:Nesting in Python and Marshmallow with a field that does not exist in the database