1

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

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')

但是,我有自己的 fields.Nested 薄子类,如下所示:

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

我将每个模式更改为使用 NestedRelationship 而不是本机Nested类型,我得到:

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

NestedRelationship 是一个相对薄的子类,我对行为的差异感到惊讶。我在这里做错了吗?我不恰当地称呼超级吗?

4

1 回答 1

0

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

于 2016-11-30T23:50:48.760 回答