如何解决这个具体的python循环导入?

问题描述 投票:1回答:1

谁能帮我解决这个python循环导入的问题?

这个文件 measurement_schema.py 进口 elementary_process_schema. 和文件 elementary_process_schema.py 进口 measurement_schema.

我需要在每个声明类的最后一行使用被引用的类,例如。在每一个声明类的最后一行 测量_schema.py。 elementary_processes = fields.Nested(ElementaryProcessSchema, many=True)

完整的代码。

测量_schema.py

from marshmallow import fields

from api import ma
from api.model.schema.elementary_process_schema import ElementaryProcessSchema


class MeasurementSchema(ma.Schema):


    id = fields.Int(dump_only=True)
    name = fields.Str()
    description = fields.Str()
    created_on = fields.Str()

    elementary_processes = fields.Nested(ElementaryProcessSchema, many=True)

elementary_process_schema.py。

from marshmallow import fields

from api import ma
from api.model.schema.ar_rl_schema import ARRLSchema
from api.model.schema.data_item_schema import DataItemSchema
from api.model.schema.elementary_process_type_schema import ElementaryProcessTypeSchema
from api.model.schema.measurement_schema import MeasurementSchema


class ElementaryProcessSchema(ma.Schema):
    id = fields.Int(dump_only=True)
    name = fields.Str()
    operation = fields.Str()
    reference = fields.Str()
    created_on = fields.Str()

    elementary_process_type = fields.Nested(ElementaryProcessTypeSchema)
    data_itens = fields.Nested(DataItemSchema, many=True)
    AR_RLs = fields.Nested(ARRLSchema, many=True)

    measurement = fields.Nested(MeasurementSchema)

我知道有很多关于这个问题的主题。但是,我无法解决我的具体循环引用问题。

python circular-dependency
1个回答
1
投票

这是一个常见的ORM问题,用python通常用同样的方法解决:你用名称(字符串)而不是引用(classinstance)来识别关系。在这里的marshmallows doc里有很好的记录。

https:/marshmallow.readthedocs.ioenstablenesting.html#two-way-nesting。

总之,可以试试这样的东西(我对棉花糖的使用经验为0,所以这个没有经过测试)。

elementary_processes = fields.Nested(ElementaryProcessSchema, many=True)
# would become:
elementary_processes = fields.Nested("ElementaryProcessSchema", many=True)

measurement = fields.Nested(MeasurementSchema)
# becomes:
measurement = fields.Nested("MeasurementSchema")
© www.soinside.com 2019 - 2024. All rights reserved.