Marshmallow: Extract value from field Nested

Created on 18 Oct 2019  路  1Comment  路  Source: marshmallow-code/marshmallow

I have next structure object

class A(Schema):
    people = field.Nested(PeopleSchema, only=('id', 'name',))
    age = field.Integer()

now run

A().dump(object).data

and i get

{people:{id:0, name:Name}, age:100}

But i want next structure

{id:0, name:Name, age:100}

Thanks
I use 2 version

question

Most helpful comment

@alCheban you can try to use the @post_dump decorator to create the data structure you want, like this:

from marshmallow import Schema, fields, post_dump
...

class A(Schema):
    people = field.Nested(PeopleSchema, only=('id', 'name',))
    age = field.Integer()

    @post_dump
    def make_dump(self, data):
        return {
            'id': data['people']['id'],
            'name': data['people']['name'],
            'age': data['age']
        }

>All comments

@alCheban you can try to use the @post_dump decorator to create the data structure you want, like this:

from marshmallow import Schema, fields, post_dump
...

class A(Schema):
    people = field.Nested(PeopleSchema, only=('id', 'name',))
    age = field.Integer()

    @post_dump
    def make_dump(self, data):
        return {
            'id': data['people']['id'],
            'name': data['people']['name'],
            'age': data['age']
        }
Was this page helpful?
0 / 5 - 0 ratings