如何在python flask sqlalchemy棉花糖应用程序中将一个属性对象数组呈现为平面数组?
我是第一次写网络应用程序。使用烧瓶,SQLAlchemy,棉花糖作为我的主要包装。我有一个嵌套的模式,但在父页面中我没有显示子项,但我希望将所有子项ID放入父项中,以便在详细信息页面中可以加载所有子项。我减少了子对象以只返回ID,但我不希望将它们作为一个属性对象,而是希望使用ids数组 我如何像这样更改JSON如何在python flask sqlalchemy棉花糖应用程序中将一个属性对象数组呈现为平面数组?,python,flask,sqlalchemy,marshmallow,Python,Flask,Sqlalchemy,Marshmallow,我是第一次写网络应用程序。使用烧瓶,SQLAlchemy,棉花糖作为我的主要包装。我有一个嵌套的模式,但在父页面中我没有显示子项,但我希望将所有子项ID放入父项中,以便在详细信息页面中可以加载所有子项。我减少了子对象以只返回ID,但我不希望将它们作为一个属性对象,而是希望使用ids数组 我如何像这样更改JSON { "description": "Report Name", "id": 1, "load_date_time": "2019-02-12T05:14:28+00:00",
{
"description": "Report Name",
"id": 1,
"load_date_time": "2019-02-12T05:14:28+00:00",
"children": [
{
"id": 1
},
{
"id": 2
},
{
"id": 3
}
],
"publish_date_time": "2018-09-03T00:00:00+00:00",
"summary": "Summary will also be present. Usually two to three brief sentences about the content on the detail page."
}
对,
棉花糖模式:
class ChildIdSchema(ma.Schema):
class Meta:
# Fields to expose
fields = ('id', )
ordered = True
class ParentSchema(ma.Schema):
children = fields.Nested('ChildIdSchema', many=True)
class Meta:
# Fields to expose
fields = ('id', 'description', 'children', 'summary', 'load_date_time', 'publish_date_time')
ordered = True
您可以使用列表理解来完成此操作,如下所示:
d['children']=[v代表d中的child['children']代表k,v代表child.items()]
如果您使用的是棉花糖3,您可以使用该字段
对于棉花糖2,仅使用参数
即可
我没有编写任何循环或任何东西,数据来自数据库mysql,我有模式将数据呈现给json。正在用模式更新我的问题。抱歉,我不确定您想要完成什么。听起来在制作json文件的过程中还需要做一些其他的事情,这里没有足够的信息来帮助你。如果你想再看一次,我已经更新了我的问题。谢谢你的建议。这是我的第一个Python代码。我自己也有点困惑。但我会尽量更新我的问题。
class ChildIdSchema(ma.Schema):
class Meta:
# Fields to expose
fields = ('id', )
ordered = True
class ParentSchema(ma.Schema):
children = fields.Nested('ChildIdSchema', many=True)
class Meta:
# Fields to expose
fields = ('id', 'description', 'children', 'summary', 'load_date_time', 'publish_date_time')
ordered = True
# 2.x
class ParentSchema(ma.Schema):
children = fields.Nested('ChildIdSchema', many=True, only='id')
# 3.x
class ParentSchema(ma.Schema):
children = fields.Pluck('ChildIdSchema', 'id', many=True)