[英]Circular import with Marshmallow nested relations
所以問題來了。 想象一下,我有三個模式模塊。 例如。
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
:
from models import C
class CSchema(ModelSchema):
class Meta:
model = C
text = fields.String(required=True)
bs = fields.Nested('BSchema', many=True, dump_only=True)
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
和c.py
,但我也需要在那里排除關系鍵。 在這種情況下如何避免循環導入?
您聲明您的問題是您無法“將BSchema
導入 a.py 和 c.py”,但似乎ASchema
和CSchema
依賴的是類B
(未在您的代碼段中的任何位置定義),而不是類BSchema
,因此您的選擇之一是將“模型”類定義與“ModelSchema”類定義分開 - 這樣您就有了包“a”、“b”和“c”,每個包都帶有子模塊“models.py”和“ schemas.py”,“schemas.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
)
注意
這里的“排除”是fields.Nested()
的關鍵字參數,而不是嵌套Schema
和
fields.Nested()
第一個參數應該是Schema
類或Schema
類名,而不是Schema
實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.