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

2024-04-28 08:56:31 发布

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

有人能帮我完成这个python循环导入吗

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

我需要在每个声明类的最后一行中使用引用的类。e、 g.度量值_schema.py的最后一行:elementary_processes = fields.Nested(ElementaryProcessSchema, many=True)

完整代码:

measurement\u 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)

基本过程模式.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)

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


Tags: frompyimportapitruefieldsmodelschema
1条回答
网友
1楼 · 发布于 2024-04-28 08:56:31

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

https://marshmallow.readthedocs.io/en/stable/nesting.html#two-way-nesting

简言之,试试这样的方法(我对棉花糖没有任何经验,所以这是没有经过测试的):

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

相关问题 更多 >