Python SQLAlchemy InvalidRequestError在不同的包中

Python SQLAlchemy InvalidRequestError在不同的包中,python,flask,sqlalchemy,Python,Flask,Sqlalchemy,我有3个单独的文件包,如下所示: -- base | - class BaseDb(db.Model) | -- pkg1 | - class A(BaseDb) | -- pkg2 | - class B(BaseDb) where db is initialized as: db = SQLAlchemy(app) in some other __init__.py class A(BaseDb): __tablename__ = "a" x = relationship(

我有3个单独的文件包,如下所示:

-- base
|  - class BaseDb(db.Model)
|
-- pkg1
|  - class A(BaseDb)
|
-- pkg2
|  - class B(BaseDb)

where db is initialized as: db = SQLAlchemy(app) in some other __init__.py

class A(BaseDb):
  __tablename__ = "a"
  x = relationship("B", back_populates="y")

class B(BaseDb):
  __tablename__ = "b"
  y = relationship("A", back_populates="x")
显示以下错误:

sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class A->x'. Original exception was: When initializing mapper mapped class Loan->loans, expression 'B' failed to locate a name ("name 'B' is not defined"). If this is a class name, consider adding this relationship() to the <class 'A'> class after both dependent classes have been defined
sqlalchemy.exc.InvalidRequestError:一个或多个映射程序未能初始化-无法继续初始化其他映射程序。触发映射器:“映射类A->x”。最初的异常是:初始化映射器映射的类Loan->loans时,表达式“B”找不到名称(“未定义名称“B”)。如果这是类名,则在定义了依赖类之后,考虑将此关系()添加到类中。
当所有的BaseDb、A和B都在同一个包中定义时,这可以正常工作,因此关系正常。许多较老的帖子建议使用
声明性的\u base
,但在初始化
模型时,
SQLAlchemy
在其init中也显式地调用了这一点

我知道抛出这个错误是因为在执行A时还没有加载B。有什么办法让它工作吗?我希望避免将它们放在同一个包中,以实现更好的模块化。

这不是因为“执行”,而是因为在加载所有模型之前使用了模型(在查询中)。使用它们是触发因素。确保所有模型在首次使用之前都已加载的一种方法是让父模块/包(属于
pkg1
pkg2
)导入其
\uuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu(在查询中)在它们全部加载之前。使用它们是什么触发因素。确保所有模型在第一次使用之前加载的一种方法是拥有父模块/包(属于
pkg1
pkg2
)导入其
\uuuu init\uuuuuuuy.py中的所有模型,因此当您导入一个模型时,它们都会被拉入。

相关:相关: