marshmallow-mongoengine icon indicating copy to clipboard operation
marshmallow-mongoengine copied to clipboard

How to add post_dump / post_load methods to a `marshmallow-mongoengine` schema?

Open lafrech opened this issue 8 years ago • 2 comments

Hi.

marshmallow-mongoengine uses Marshmallow's post_dump / post_load decorators.

The docs say:

The invocation order of decorated methods of the same type is not guaranteed. If you need to guarantee order of different processing steps, you should put them in the same processing method.

What if I'd like to add a post load processing? If I add a method to the schema that I decorate with the post_load decorator, how do I know whether it will be called before or after MongoEngine object instantiation?

From a test I just made, my own decorated method was called before object instantiation, but is this reliable? And what if I wanted to have it called afterwards?

Should marshmallow-mongoengine expose its own plugs, like this?

    @ma.post_load
    def _make_object(self, data):
        self.pre_post_load(data)
        if self.opts.model_build_obj and self.opts.model:
            return self.opts.model(**data)
        else:
            return data
        self.post_post_load(data)

Then in my subclass, I'd declare

    def pre_post_load(data):
        #whatever I want to do
        ...
        return data

Just an example to illustrate the idea. The names are dummy, and it could be more elegant with decorators as in Marshmallow.

I know the use of those decorators in marshmallow-mongoengine was blessed by @sloria, and I may be totally missing something obvious, but the way is understand things now is that using marshmallow-mongoengine takes away the possibility of using those decorators for other post treatments.

lafrech avatar Jun 22 '16 16:06 lafrech