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

Pass marshmallow context into nested schemas? #138

Closed
ghostwheel42 opened this issue Feb 25, 2021 · 2 comments · Fixed by #160
Closed

Pass marshmallow context into nested schemas? #138

ghostwheel42 opened this issue Feb 25, 2021 · 2 comments · Fixed by #160

Comments

@ghostwheel42
Copy link
Contributor

Hi,

I'm using a marshmallow context to alter serialization and de-serialization of many schemas (see example below).
Would it be possible to include the context of the parent schema when creating nested schemas?

nested_instance = nested(only=only, exclude=exclude)

Using nested_instance = nested(only=only, exclude=exclude, context=obj.context) would do just fine.

Alex

from pprint import pprint
from marshmallow import Schema, fields
from marshmallow_jsonschema import JSONSchema

class UserSchema(Schema):

    def __init__(self, *args, **kwargs):
        if kwargs.get('context', {}).get('hide', False):
            kwargs.setdefault('exclude', []).append('birthday')
        super().__init__(*args, **kwargs)

    username = fields.String()
    age = fields.Integer()
    birthday = fields.Date()

user_schema = UserSchema()
json_schema = JSONSchema()
pprint(json_schema.dump(user_schema))

context = {
    'hide': True,
}
user_schema = UserSchema(context=context)
pprint(json_schema.dump(user_schema))
@ghostwheel42
Copy link
Contributor Author

Hi @fuhrysteve.
Would it be possible to include this small change or is there another way to achieve what I want to do?
I can create a PR if you like.

Alex

@fuhrysteve
Copy link
Owner

Pull requests are welcome! Thanks!

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

Successfully merging a pull request may close this issue.

2 participants