0

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?


Mikev
  • 2,012
  • 1
  • 15
  • 27
maslak
  • 1,115
  • 3
  • 8
  • 22

1 Answers1

3

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',))
Stephen Fuhry
  • 12,624
  • 6
  • 56
  • 55