In
#python #marshmallow #fields #fields_method
marshmallow
you can have a schema field which can be filled with a method output. Let's see with an example:class AuthorSchema(Schema):As you see
id = fields.Int(dump_only=True)
first = fields.Str()
last = fields.Str()
formatted_name = fields.Method("format_name", dump_only=True)
def format_name(self, author):
return "{}, {}".format(author.last, author.first)
formatted_name
field is filled by a method called format_name
. Examples are endless, you can calculate average score based on the given scores for instance.#python #marshmallow #fields #fields_method