Pass marshmallow context into nested schemas?
ghostwheel42 opened this issue · 2 comments
ghostwheel42 commented
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?
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 commented
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 commented
Pull requests are welcome! Thanks!