Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python-marshmallow: deserializing nested schema with only one exposed key

I am trying to serialize a list of nested objects as scalar values by taking only one field from the nested item. Instead of [{key: value}, ...] I want to receive [value1, value2, ...].

Code:

from marshmallow import *

class MySchema(Schema):
    key = fields.String(required=True)

class ParentSchema(Schema):
    items = fields.Nested(MySchema, only='key', many=True)

Given the above schemas, I want to serialize some data:

>>> data = {'items': [{'key': 1}, {'key': 2}, {'key': 3}]}
>>> result, errors = ParentSchema().dump(data)
>>> result
{'items': ['1', '2', '3']}

This works as expected, giving me the list of scalar values. However, when trying to deserialize the data using the models above, the data is suddenly invalid:

>>> data, errors = ParentSchema().load(result)
>>> data
{'items': [{}, {}, {}]}
>>> errors
{'items': {0: {}, '_schema': ['Invalid input type.', 'Invalid input type.', 'Invalid input type.'], 1: {}, 2: {}}}

Is there any configuration option I am missing or is this simply not possible?

like image 731
Birne94 Avatar asked Oct 18 '22 03:10

Birne94


1 Answers

For anyone stumbling across the same issue, this is the workaround I am using currently:

class MySchema(Schema):
    key = fields.String(required=True)

    def load(self, data, *args):
        data = [
            {'key': item} if isinstance(item, str) else item
            for item in data
        ]
        return super().load(data, *args)


class ParentSchema(Schema):
    items = fields.Nested(MySchema, only='key', many=True)
like image 51
Birne94 Avatar answered Nov 15 '22 05:11

Birne94