Scott
Scott

Reputation: 77

how to use marshmallow post_load? no attribute 'data'

From the docs under 'Deserializing to Objects':

from marshmallow import Schema, fields, post_load


class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()
    created_at = fields.DateTime()

    @post_load
    def make_user(self, data, **kwargs):
        return User(**data)

But I when I run this code, I get: AttributeError: 'User' object has no attribute 'data'

What am I missing?

Upvotes: 0

Views: 7935

Answers (1)

Baruch Spinoza
Baruch Spinoza

Reputation: 200

Try returning the data dictionary instead of an instance of your model.

I stumbled upon issue this while using marshmallow-sqlalchemy and flask-marshmallow

from marshmallow import Schema, fields, post_load


class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()
    created_at = fields.DateTime()

    @post_load
    def make_user(self, data, **kwargs):
        data['extra_attribute'] = 'extra value'
        return data

Upvotes: 1

Related Questions