Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I add a field containing a list of dictionaries in Marshmallow Python?

In Marshmallow in order to have a list field you can use:

include_in = fields.List(cls_or_instance=fields.Str(),
                         default=['sample1', 'sample2'])

This is OK, but I have a new requirement to have a list of dictionaries in a field. A sample payload:

[{
  "name": "Ali",
  "age": 20
},
{
  "name": "Hasan",
  "age": 32
}]

This payload is part of the bigger schema, so now the question is how should I add and validate such a field?


EDIT-1: I went a step further and could find out that there is a Dict field type in Marshmallow so until now I have the below code sample:

fields.List(fields.Dict(
        keys=fields.String(validate=OneOf(('name', 'age'))),
        values=fields.String(required=True)
))

Now new problem arise and I cannot set different data types for fields in the dictionary (name and age). I'd be happy if someone could shed some light on this.

like image 972
Alireza Avatar asked Jul 10 '19 08:07

Alireza


1 Answers

If the items in the list have the same shape, you can use a nested field within fields.List, like so:

class PersonSchema(Schema):
    name = fields.Str()
    age = fields.Int()

class RootSchema(Schema):
    people = fields.List(fields.Nested(PersonSchema))
like image 182
Steve L Avatar answered Oct 09 '22 06:10

Steve L