棉花糖嵌套后_加载对象的创建方法

问题描述 投票:3回答:1

我正在开发一个处理嵌套数据结构的API。当我尝试使用marshmallow时,我很难想出一个解决方案来创建具有父实例引用的嵌套模型实例。Marshmallow的post_load按照从子实例到父实例的顺序操作,而不是从父实例到子实例。有什么方法可以反过来吗?我想先把父实例序列化,然后把它作为上下文传递给子实例。

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)
python flash sqlalchemy marshmallow
1个回答
0
投票

我认为,你不需要post_load,因为没有类要从这个模式中反序列化,所以只要删除它,它应该可以工作.如果你打算dserialize和保持它到任何类,你需要在post_load装饰器中返回,例如:

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)
© www.soinside.com 2019 - 2024. All rights reserved.