List(Nested()) 在嵌套架构中不使用 `many`
作者: ThiefMaster创建于 2021年4月30日更新于 2025年11月10日
from marshmallow import Schema, fields, post_dump
class ItemSchema(Schema):
id = fields.Integer()
name = fields.String()
@post_dump(pass_many=True)
def query_extra_data(self, data, many, **kwargs):
print(f'post_dump called: {many=} {data=}')
class TestSchema(Schema):
items = fields.List(fields.Nested(ItemSchema))
data = {'items': [
{'id': 1, 'name': 'foo'},
{'id': 2, 'name': 'bar'},
{'id': 3, 'name': 'snafu'},
]}
TestSchema().dump(data)这会产生以下输出:
post_dump called: many=False data={'name': 'foo', 'id': 1}
post_dump called: many=False data={'name': 'bar', 'id': 2}
post_dump called: many=False data={'name': 'snafu', 'id': 3}但是,我希望得到以下结果:
post_dump called: many=True data=[{'name': 'foo', 'id': 1}, {'name': 'bar', 'id': 2}, {'name': 'snafu', 'id': 3}]当 post_dump 钩子从数据库查询数据时,这是一个问题,因为我最终会得到 n 个独立查询,而不是一个单个查询,其中我可以使用 IN 来高效地获取列表中的所有对象的数据。
内容来源: marshmallow-code/marshmallow