【问题标题】:Changing the information before serialization在序列化之前更改信息
【发布时间】:2021-02-06 03:40:08
【问题描述】:

我有一个数据库模型,例如:-

class Script(db.Model):
   path = db.Column(db.String(50))

还有一个像这样的序列化器:-

class ScriptSchema(ma.Schema):
   class Meta:
      fields = (
          'path'
   )

我的问题是,当我在查询后转储数据时:-

all_scripts_orm = Script.query.all()
all_scripts = ScriptSchema(many=True).dump(all_scripts_orm)

我以

的形式获取数据
[
   {"path": "Sample_folder/Sample_Script_1.txt"},
   {"path": "Sample_folder/Sample_script_2.txt"}
]

但我希望能够只提取脚本的名称并对其进行序列化

[
    {"path": "Sample_script_1.txt"},
    ...
]

我不想为脚本模型中的名称创建另一列,我该如何解决这个问题?

【问题讨论】:

    标签: python-3.x flask-sqlalchemy marshmallow flask-marshmallow


    【解决方案1】:

    使用Function 字段,文档示例here 和文档here。例如:

    from os import path as op
    
    class ScriptSchema(ma.Schema):
       class Meta:
          fields = (
              'path'
       )
    
       path = fields.Function(lambda obj: op.basename(obj.path))
    

    【讨论】:

    • 非常感谢 pjcunningham。
    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    相关资源
    最近更新 更多