I have a database model like:-
class Script(db.Model):
path = db.Column(db.String(50))
and a serializer like:-
class ScriptSchema(ma.Schema):
class Meta:
fields = (
'path'
)
My question is that when I dump the data after querying:-
all_scripts_orm = Script.query.all()
all_scripts = ScriptSchema(many=True).dump(all_scripts_orm)
I get data in the form of
[
{"path": "Sample_folder/Sample_Script_1.txt"},
{"path": "Sample_folder/Sample_script_2.txt"}
]
But I want to be able to do extract only the name of the script and serialize it
[
{"path": "Sample_script_1.txt"},
...
]
How do I approach this problem as I don't want to make another column just for name in the Script Model ?
Use a Function
field, documentation example here and documented here. For example:
from os import path as op
class ScriptSchema(ma.Schema):
class Meta:
fields = (
'path'
)
path = fields.Function(lambda obj: op.basename(obj.path))