【问题标题】:Python marshmallow cycle issues with Nested subclass嵌套子类的 Python 棉花糖循环问题
【发布时间】:2016-01-25 00:01:24
【问题描述】:

我有 3 个带有嵌套字段的棉花糖模式,它们形成了一个依赖循环/三角形。如果我使用two-way nesting 的样板,我似乎没有问题。

from marshmallow import Schema, fields
class A(Schema):
    id = fields.Integer()
    b = fields.Nested('B')

class B(Schema):
    id = fields.Integer()
    c = fields.Nested('C')

class C(Schema):
    id = fields.Integer()
    a = fields.Nested('A')

但是,我有自己的、精简的字段子类。嵌套如下所示:

from marshmallow import fields
class NestedRelationship(fields.Nested):

    def __init__(self, nested,
                 include_data=True,
                 **kwargs):

        super(NestedRelationship, self).__init__(nested, **kwargs)

        self.schema.is_relationship = True
        self.schema.include_relationship_data = include_data

我将每个 Schema 更改为使用 NestedRelationship 而不是原生的 Nested 类型,我得到:

marshmallow.exceptions.RegistryError: Class with name 'B' was not found. You may need to import the class.

NestedRelationship 是一个相对较细的子类,我对行为上的差异感到惊讶。我在这里做错了吗?我是不是叫 super 不恰当?

【问题讨论】:

    标签: python marshmallow


    【解决方案1】:

    问题在于您访问self.schema 的额外代码。当您定义 A.b 字段时,它会尝试解析它,但尚未定义。另一方面,marshmallow.fields.Nested 不会尝试在构建时解析模式,因此不存在此问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多