【问题标题】:How do I render one property object array to flat array in python flask sqlalchemy marshmallow app?如何在 python flask sqlalchemy marshmallow 应用程序中将一个属性对象数组渲染为平面数组?
【发布时间】:2019-07-18 10:48:19
【问题描述】:

我是第一次编写 Python Flask WebApp。使用 Flask、SQLAlchemy、Marshmallow 作为我的主要包。我有一个嵌套模式,但在父页面中我没有显示子页面,但我想将所有子 ID 带入父页面,以便在详细信息页面中加载所有子页面。我修剪了孩子们只返回 ids,但是我不希望它们作为一个属性对象,而是想要 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

【问题讨论】:

    标签: python flask sqlalchemy marshmallow


    【解决方案1】:

    您可以使用以下列表推导来完成此操作:

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

    【讨论】:

    • 我没有写任何循环或任何东西,数据来自数据库 mysql,我有将数据呈现到 json 的模式。用 Schemas 更新我的问题。
    • 抱歉,我不确定您要完成什么。听起来在制作 json 文件的过程中还需要做一些其他的事情,这里没有足够的信息来帮助解决这个问题。
    • 如果您想再看一遍,我已经更新了我的问题。感谢您的建议。
    • 这是我的第一个 Python 代码。我自己还有些困惑。但会尝试不断更新我的问题。
    【解决方案2】:

    如果您使用的是 marshmallow 3,则可以使用 Pluck 字段。

    对于棉花糖 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 2017-05-29
      相关资源
      最近更新 更多