Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
How to add nested documents in Marshmallow python?

books = fields.List(fields.Dict(
keys=fields.String(validate=OneOf(('title', 'author', 'publication_date'))),
values=fields.String(required=True)))


#python #data_class #marshmallow #fields #list #OneOf
In marshmallow you can have a schema field which can be filled with a method output. Let's see with an example:

class AuthorSchema(Schema):
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)


As you see 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