Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can a Nested schema serialize values from its parent? #900

Closed
bjmc opened this issue Aug 2, 2018 · 2 comments
Closed

Can a Nested schema serialize values from its parent? #900

bjmc opened this issue Aug 2, 2018 · 2 comments

Comments

@bjmc
Copy link

bjmc commented Aug 2, 2018

My apologies if this is covered in the docs somewhere and I missed it. Is it possible to have a Nested schema that refers to properties of the parent model object?

Assume you have a model that looks something like this:

class UserModel():
    name = Column(String)
    created = Column(Datetime)
    updated = Column(Datetime)

And you want to produce serialized output like:

{'meta': {'created': '2018-08-02T10:53:41',
          'updated': '2018-08-02T10:54:04'},
 'name': 'Some Name'}

If you define marshmallow schemas like:

from marshmallow import Schema, fields

class MetaSchema(Schema):
    created = fields.DateTime(dump_only=True)
    updated = fields.DateTime(dump_only=True)

class UserSchema(Schema):
     name = fields.String()
     meta = fields.Nested(MetaSchema())

But there's no "meta" attribute on the ORM object, I just want to pull out specific properties. Is there a way to tell the Nested schema that it should look for values on the parent?

A guess a more general way to phrase this question would be: How can Marshmallow handle situations where the relationships between model objects is different that the relationships in the serialized output? Should I just be coercing it into the necessary shape with @post_dump and @pre_load modifiers?

@asthasr
Copy link

asthasr commented Aug 21, 2018

I found a solution to this that allowed me to avoid using custom fields (I'm using apispec and want to minimize that where possible). I added a hook:

class SelfReferentialSchema(Schema):
    @pre_dump
    def add_self_reference(self, data):
        setattr(data, "_marshmallow_self_reference", data)

Then you can refer to this on the fields.Nested call:

class UserSchema(SelfReferentialSchema):
    name = fields.String()
    meta = fields.Nested(MetaSchema(), attribute="_marshmallow_self_reference")

Unfortunately, there's no clean way that I can see to remove this; @post_dump doesn't receive the original data.

@sloria
Copy link
Member

sloria commented Oct 18, 2018

Let's continue discussion of this in #940

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants