pythonmarshmallow

marshmallow nested change schema behavior


I would like to know how to pass context to a nested Schema field so that it serializes differently than if it was not nested.

I have a Schema subclass that adds some things in a @post_dump depending on some flag arg:

class MySchema(Schema):
    def __init__(self, flag=False, *args, **kwargs):
        self.flag = flag
        super(MySchema, self).__init__(*args, **kwargs)

     @post_dump
     def add_thing(self, data):
         if self.flag:
              #add {'NESTED' : 'some_value'} to data
         else:
              #add {'NOT_NESTED' : 'some_value'} to data
         return data

I have a standard nested schema that roughly looks like :

class ASchema(MySchema):
  id = fields.Integer()
  b  = fields.Nested(BSchema, flag=True)

class BSchema(MySchema):
  x = fields.Integer()
  y = fields.Integer()

where I end up with a serialization of ASchema that looks like :

{ 'id' : 5,
  'NOT_NESTED' : 'some_value',
  'b'  : { 'x' : 10,
           'y' : 15,
           'NOT_NESTED' : 'some_value',
         }
}

If my BSchema is Nested, I would like for the post_dump in MySchema to be able to tell via flag.

Looking at the source for fields.Nested(), it passes some **kwargs up to Field.__init__(), but in the _serialize() method, it just returns Bschema.dump().

Do I have any options for changing the serialization of a field depending on whether it is nested?


Solution

  • You can configure Nested with a schema instance, not just schema class. That way you can configure it the way you like:

    class ASchema(MySchema):
      id = fields.Integer()
      b  = fields.Nested(BSchema(flag=True))