Python 棉花糖嵌套加载后对象创建
我正在开发一个处理嵌套数据结构的API。当尝试使用棉花糖时,我很难想出一个解决方案来创建嵌套模型实例,并引用它们的父实例。棉花糖的post_加载按该顺序从子对象到父对象,而不是从父对象到子对象。有没有办法扭转这种局面?我想从序列化父对象开始,并将其作为上下文传递给子对象Python 棉花糖嵌套加载后对象创建,python,flash,sqlalchemy,marshmallow,Python,Flash,Sqlalchemy,Marshmallow,我正在开发一个处理嵌套数据结构的API。当尝试使用棉花糖时,我很难想出一个解决方案来创建嵌套模型实例,并引用它们的父实例。棉花糖的post_加载按该顺序从子对象到父对象,而不是从父对象到子对象。有没有办法扭转这种局面?我想从序列化父对象开始,并将其作为上下文传递给子对象 var_test = { "id": 1, "name": "dad a", "children_a": [ { "id": 2, "nam
var_test = {
"id": 1,
"name": "dad a",
"children_a": [
{
"id": 2,
"name": "child 1 - 2",
"grand_children_a": [
{
"id": 2,
"name": "child 1 - 2",
}
]
},
{
"id": 3,
"name": "child 2 - 2",
}
]
}
class ParentA(Schema):
id = fields.Integer()
name = fields.String()
children_a = fields.Nested('ChildrenA', many=True)
@post_load()
def pl_handler(self, data):
# create Parent A
return data
class ChildrenA(Schema):
id = fields.Integer()
name = fields.String()
grand_children_a = fields.Nested('GrandchildrenA', many=True)
@post_load()
def pl_handler(self, data):
# create child of Parent A
return data
class GrandchildrenA(Schema):
id = fields.Integer()
name = fields.String()
@post_load()
def pl_handler(self, data):
# create child of ChildrenA
return "grand child string"
var_s = ParentA()
var_s.load(var_test)
我认为,您不需要post_加载,因为没有将从该模式反序列化的类,所以只需删除它,它就可以工作了。 如果您计划将其序列化并保留到任何类,则需要在post_load decorator中返回,例如:
from marshmallow import Schema, fields, INCLUDE, post_load
class Author:
def __init__(self, name, age):
self.name = name
self.age = age
class Book:
def __init__(self, title, description, author):
self.title = title
self.description = description
self.author = author
class AuthorSchema(Schema):
name = fields.Str()
age = fields.Int()
@post_load
def load_author(self, data, **kwargs):
return Author(**data)
class BookSchema(Schema):
title = fields.Str()
description = fields.Str()
author = fields.Nested(AuthorSchema)
@post_load
def load_book(self, data, **kwargs):
return Book(**data)
data = {
"title": "Test Book",
"description": "A book Test",
"author": {"name": "Vivek", "age": 35},
}
book = BookSchema(unknown=INCLUDE).load(data )
print(book)
print(book.author)
print(book.author.name)
你明白了吗?我仍然使用棉花糖进行验证序列化/反序列化,但使用链接post_加载不是一个解决方案。原始问题中的代码示例有点不正确。不幸的是,这并不能解决问题。最初的问题试图解决这样一个问题:当使用嵌套序列化程序时,棉花糖后期加载从底部/子级开始,然后向上运行。在使用嵌套的rest结构时,您应该从顶部开始保存,然后逐步向下到子级以建立关系。这是很有可能的,但仅在其自身上使用post_加载并不太有效。