我是第一次编写 Python Flask WebApp。使用 Flask、SQLAlchemy、Marshmallow 作为我的主要包。我有一个嵌套模式,但在父页面中我没有显示子项,但我想将所有子项 ID 放入父项中,以便在详细信息页面中我可以加载所有子项。我将子项缩减为只返回 id,但我不想将它们作为一个属性对象,而是想要 ids 数组。
如何像这样更改 JSON,
{
"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."
}
到,
{
"description": "Report Name",
"id": 1,
"load_date_time": "2019-02-12T05:14:28+00:00",
"children": [
1,
2,
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
最佳答案
如果您使用的是 marshmallow 3,则可以使用 Pluck
的字段。
对于 marshmallow 2,使用 only
参数到 Nested
.
# 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)
关于python - 如何在 python flask sqlalchemy marshmallow 应用程序中将一个属性对象数组渲染为平面数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54859312/