如何解决这个特定的python循环导入?

时间:2020-05-07 15:22:36

标签: python circular-dependency

有人可以帮助我进行此python循环导入吗?

文件measurement_schema.py导入elementary_process_schema。文件elementary_process_schema.py会导入measurement_schema

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

的最后一行

完整代码:

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

我知道关于这个问题有很多话题。但是,我无法解决我的特定循环参考问题。

1 个答案:

答案 0 :(得分:1)

这是ORM的常见问题,而对于python,通常可以通过相同的方式解决:通过名称(字符串)而不是引用(类/实例)识别关系。棉花糖文档中对此有很好的记录:

https://marshmallow.readthedocs.io/en/stable/nesting.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")
相关问题