flask-marshmallow在一个模式中的两个数据库对象 [英] flask-marshmallow two db objects in one schema

查看:56
本文介绍了flask-marshmallow在一个模式中的两个数据库对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试序列化该对象,这是两个表之间的联接的结果:

I'm trying to serialize this object, which is a result of a join between two tables:

query_response = [(<Company 2>, <Detail 1>), (<Company 3>, <Detail 2>)]

我正在使用以下模式:

class CompanyCompleteSchema(Schema):
    company = fields.Nested(CompanySchema)
    detail = fields.Nested(DetailSchema)

companies_complete_schema = CompanyCompleteSchema(many=True)

基本上,我想为联接查询提供一个模式.我正在使用:

Basically, I'd like to have one schema for the join query. I'm using:

data = companies_complete_schema.dump(query_response)

它不起作用,我无法解决问题.它只是返回:

It doesn't work and I can't figure out the problem. It just returns:

[{}, {}]

任何建议都将受到高度赞赏.谢谢.

Any suggestion is highly appreciated. Thanks.

推荐答案

many = True设置棉花糖对提供的列表进行迭代,并反序列化每个对象.

many=True sets Marshmallow to iterate the list provided, and deserialize each object.

该列表中的对象的格式为({},{}).棉花糖期望它的格式为{'company':{},'detail':{}}.因此,要使其正常工作,您必须先将查询结果转换为字典,然后再将其传递给dump方法.我希望以下内容能为您服务...

An object in that list is of the form ({}, {}). Marshmallow is expecting it to have the form {'company': {}, 'detail': {}}. So, to get this to work, you'll have to convert your query result to a dictionary before passing them to the dump method. I would expect the following to work for you...

data, errors = companies_complete_schema.dump([{'company': x[0], 'detail': x[1]} for x in query_response])

这篇关于flask-marshmallow在一个模式中的两个数据库对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆