Search code examples
pythonpython-3.xsqlalchemymarshmallow

load_only, dump_only for Nested fields


Is there any way in marshmallow-sqlalchemy to specify load_only or dump_only fields for Nested (foos) when serializing/deserializng Bar?

class FooSchema(BaseSchema):
    class Meta(BaseSchema.Meta):
        model = Foo
        fields = ('id', 'name', 'date', 'clients')


class BarSchema(BaseSchema):
    class Meta(BaseSchema.Meta):
        model = Bar
        fields('id',)
    foos = Nested(FooSchema, many=True, only=('id', 'name'))
# is there a way to add to foos field something like load_only=('id',)
# without changing FooSchema?



Solution

  • I recommend against specifying only in the definition of a Nested relationship. Use exclude to prevent circular references and specify which fields you want only explicitly each time you are serializing.

    Additionally, you generally shouldn't need to specify fields - marshmallow-sqlalchemy gives you that for free for most fields. Here's how I'd refactor the above:

    class FooSchema(BaseSchema):
        bar = Nested('myproject.schemas.bar.BarSchema', exclude=('foos',))
        class Meta(BaseSchema.Meta):
            model = Foo
            dump_only = ('id',)
    
    
    class BarSchema(BaseSchema):
        class Meta(BaseSchema.Meta):
            model = Bar
            dump_only = ('id',)
        # don't specify `only` here:
        foos = Nested(FooSchema, many=True, exclude=('bar',))