load_only、dump_only 用于嵌套字段
load_only, dump_only for Nested fields
marshmallow-sqlalchemy 中是否有任何方法可以在 serializing/deserializng Bar 时为嵌套 (foos) 指定 load_only 或 dump_only 字段?
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?
我建议不要在 Nested
关系的定义中指定 only
。使用 exclude
防止循环引用并在每次序列化时明确指定您想要的字段 only
。
此外,您通常不需要指定 fields
- marshmallow-sqlalchemy
为您免费提供大多数字段。以下是我重构上述内容的方式:
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',))
marshmallow-sqlalchemy 中是否有任何方法可以在 serializing/deserializng Bar 时为嵌套 (foos) 指定 load_only 或 dump_only 字段?
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?
我建议不要在 Nested
关系的定义中指定 only
。使用 exclude
防止循环引用并在每次序列化时明确指定您想要的字段 only
。
此外,您通常不需要指定 fields
- marshmallow-sqlalchemy
为您免费提供大多数字段。以下是我重构上述内容的方式:
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',))