How to combine nested object with parent in marshmallow (+ sqlalchemy)?

From his example https://marshmallow.readthedocs.org/en/latest/quickstart.html#nesting-serializers

How do you get the merged result instead of the nested one? Expected Result:

user = User(name="Monty", email="monty@python.org")
blog = Blog(title="Something Completely Different", author=user)
serialized = BlogSerializer(blog)
serialized.data
# {'created_at': 'Sun, 10 Nov 2013 16:10:57 -0000',
#  'email': u'monty@python.org',
#  'name': u'Monty',
#  'title': u'Something Completely Different'}

      

+3


source to share


2 answers


Instead of changing the way Marshmallow serializations are generated, I decided to use data_handler.
This may seem like a hack (tbh it is), but I really need the data to be flattened.

This solution has the advantage that it is easy to remove the hack when I don't need it.

@BlogSerializer.data_handler
def flatten(serializer, data, obj):
    if 'author' in data:
        author = data['author']
        del data['author']
        return dict(author, **data)
    else:
        return data

      



You can easily make this method more general, with the list of attributes flattened. I don't need this level of abstraction at the moment.

Thanks @justanr for the tip.

+2


source


You will have to serialize each property of the nested object separately. The easiest way, if you want to go this route, is to define a method field for each field that you would like to "concatenate" into the main serializer. Although, with enough hack in the custom field, you could manage this for you.



However, this plays against the strength of the marshmallow, allowing you to make complex patterns quickly and easily.

+1


source







All Articles