5

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?

2
  • I'm not entirely sure I understand Your questions, but can You confirm it sounds you are asking about this test example: github.com/marshmallow-code/marshmallow/blob/… ( test_default_many_symmetry ) Is that correct ?
    – galuszkak
    Oct 26, 2017 at 10:02
  • The test you have linked serializes each user to {"name": "name1"}. What I would like to do is to serialize each user to "name1", especially for the many=True use case, which should dump to ["King Arthur", "Sir Lancelot"] instead of [{'name': 'King Arthur'}, {'name': 'Sir Lancelot'}]
    – Birne94
    Oct 26, 2017 at 10:38

1 Answer 1

3

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.