具有棉花糖嵌套关系的循环导入

2024-04-27 05:12:59 发布

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

所以问题就在这里。假设我有三个模式模块。例如。在

a.py

from models import A

class ASchema(ModelSchema):
    class Meta:
        model = A

    text = fields.String(required=True)
    bs = fields.Nested('BSchema', many=True, dump_only=True)

c.py

^{pr2}$

b.py

from models import B

class BSchema(ModelSchema):
    class Meta:
        model = B

    text = fields.String(required=True)
    as = fields.Nested(ASchema(exclude=ASchema.Meta.model.relations_keys), many=True, dump_only=True)
    cs = fields.Nested(CSchema(exclude=CSchema.Meta.model.relations_keys), many=True, dump_only=True)

问题是我不能将BSchema导入a.py和{},但我也需要排除关系键。在这种情况下,如何避免循环导入?在

  • 我知道有一个选项可以将所有内容都包含在一个模块中,但这是我最后的选择。在

Tags: 模块frompytrueonlyfieldsmodelmodels
1条回答
网友
1楼 · 发布于 2024-04-27 05:12:59

你说你的问题是你不能“导入BSchema到a.py和c.py”,但是看起来ASchema和{}依赖的是类B(在你的代码段中没有定义),而不是类BSchema,因此,您的一个选择是将“model”类定义从“ModelSchema”类定义中分离出来,这样您就有了“a”、“b”和“c”包,每个包都有子模块模型.py“和”模式.py“,带”模式.py“模块”依赖于“模型”,但“模型”不依赖于“模式”。在

这就是说,当你有如此紧密的耦合时,通常意味着你的类真的属于同一个模块。。。在

编辑:看起来你的模型已经在一个不同的模块中了,所以我真的不明白是什么阻止你直接在“模式”模块中引用模型,例如:

# a.py
from wherever import ModelSchema, fields
from models import A, B

class ASchema(ModelSchema):
    class Meta:
        model = A

    text = fields.String(required=True)
    bs = fields.Nested(
            'BSchema', 
            exclude=B.relations_keys,
            many=True, 
            dump_only=True
            )

# c.py
from wherever import ModelSchema, fields
from models import C, B

class ASchema(ModelSchema):
    class Meta:
        model = C

    text = fields.String(required=True)
    bs = fields.Nested(
            'BSchema', 
            exclude=B.relations_keys,
            many=True, 
            dump_only=True
            )

# b.py
from wherever import ModelSchema, fields
from models import A, B, C

class BSchema(ModelSchema):
    class Meta:
        model = B

    text = fields.String(required=True)
    as = fields.Nested(
            "ASchema", 
            exclude=A.relations_keys, 
            many=True, 
            dump_only=True
            )
    cs = fields.Nested(
             "CSchema", 
             exclude=C.relations_keys, 
             many=True, 
             dump_only=True
             )

请注意

  1. 这里“exclude”是fields.Nested()的关键字arg,而不是嵌套的Schema

  2. fields.Nested()第一个参数应该是SchemaSchema类名,不是aSchema实例

相关问题 更多 >