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

标签 python flask sqlalchemy marshmallow

我是第一次编写 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/

相关文章:

python - 有没有比 Cairo 更好的用 Python 绘制矢量图形的库?

python - Python中的自定义异常似乎不遵循 "its easier to ask for forgiveness"?

python - pytorch cnn模型在loss.backward()处停止而没有任何提示?

python - Gunicorn 卡在带有 Flask 应用程序的 docker run 命令上

python - Flask:多个蓝图相互干扰

python - 将 sympy 结果作为三角函数而不是复杂的日志

python - 为什么语法从 flask.ext.* 更改为 flask_*?

python - 在 SQLAlchemy 中过滤大型关系子查询

python - 如何关闭 SQLAlchemy session ?

python - 在sqlalchemy中批量更新的where子句中添加多个条件