循环进口豆豆ODM

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

我需要在我的 MongoDB 模式中使用交叉引用。我使用 beanie 作为 ODM。这是我的模型:

entity.py

from beanie import Document

class Entity(Document):
    path: List["Folder"] = []

文件夹.py

from entity import Entity

class Folder(Entity)
    pass

init_beanie.py

import beanie
from motor.motor_asyncio import AsyncIOMotorClient
from entity import Entity
from folder import Folder

models = [Entity, Folder]

async def init_beanie():
    client = AsyncIOMotorClient("mongo-uri")

    Entity.update_forward_refs(Folder=Folder)

    await beanie.init_beanie(database=client["mongo-db-name"], document_models=models)

main.py

from fastapi import FastAPI
from init_beanie import init_beanie

my_app = FastAPI()

@my_app.on_event("startup")
async def init():
    await init_beanie()

但是当我启动我的应用程序时出现错误:

  ...
  File "pydantic/main.py", line 816, in pydantic.main.BaseModel.update_forward_refs
  File "pydantic/typing.py", line 553, in pydantic.typing.update_model_forward_refs
  File "pydantic/typing.py", line 519, in pydantic.typing.update_field_forward_refs
  File "pydantic/typing.py", line 65, in pydantic.typing.evaluate_forwardref
  File "/usr/local/lib/python3.9/typing.py", line 554, in _evaluate
    eval(self.__forward_code__, globalns, localns),
  File "<string>", line 1, in <module>
NameError: name 'Folder' is not defined

我做错了什么?

python pydantic circular-reference
© www.soinside.com 2019 - 2024. All rights reserved.