在棉花糖中,有没有方法将当前对象传递给 Nested 字段以生成人工嵌套序列化?例如,考虑我正在序列化的对象:
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" } }
AddressSchema 在里面 ExampleSchema ,就像这样:
AddressSchema
ExampleSchema
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 添加自引用属性并将字段指向该属性的钩子:
@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)