棉花糖-sqlalchemy中有什么方法可以在序列化/反序列化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?
答案 0 :(得分:1)
我建议不要在only
关系的定义中指定Nested
。使用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',))