嵌套字段的load_only,dump_only

时间:2019-05-10 09:44:55

标签: python python-3.x sqlalchemy marshmallow

棉花糖-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?


1 个答案:

答案 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',))