仅加载_,仅转储嵌套字段

2024-10-03 11:21:28 发布

您现在位置:Python中文网/ 问答频道 /正文

marshmallow sqlalchemy中有没有方法在序列化/反序列化zng Bar时为嵌套(foos)指定只加载或只转储字段吗?在

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?



Tags: tonameidonlyfieldsmodel序列化sqlalchemy
1条回答
网友
1楼 · 发布于 2024-10-03 11:21:28

我建议不要在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',))

相关问题 更多 >