如何在 python flask sqlalchemy marshmallow 应用程序中将一个 属性 对象数组渲染为平面数组?

How do I render one property object array to flat array in python flask sqlalchemy marshmallow app?

我是第一次写 Python Flask WebApp。使用 Flask、SQLAlchemy、Marshmallow 作为我的主要包。我有一个嵌套模式,但在父页面中我没有显示子项,但我想将所有子项 ID 放入父项中,以便在详细信息页面中我可以加载所有子项。我将子项缩减为只有 return 个 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

您可以使用列表理解来完成此操作,如下所示:

d['children'] = [v for child in d['children'] for k,v in child.items()]

如果您使用的是 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)