Search code examples
pythonmarshmallow

Marshmallow field lookup on deserialisation


Is it possible to perform input data lookups with marshmallow schemas ? The following does not work.. :

class ParentSchema(Schema):
    child_name = fields.String(data_key="child.fname")

Then during deserialisation:

data = {"child": {"fname": "John", "lname": "Doe"}}
ParentSchema().load(data)

The result is {}.

marshmallow-v3.14.1


Solution

  • You can achieve this using fields.Function:

    class ParentSchema(Schema):
        child_name = fields.Function(data_key="child",
                                     deserialize=lambda child: child["fname"])
    
    data = {"child": {"fname": "John", "lname": "Doe"}}
    ParentSchema().load(data)
    

    And the result is {'child_name': 'John'}.