SQLAlchemy 找不到类名
简单来说,我有以下的类结构(在一个文件里):
Base = declarative_base()
class Item(Base):
__tablename__ = 'item'
id = Column(BigInteger, primary_key=True)
# ... skip other attrs ...
class Auction(Base):
__tablename__ = 'auction'
id = Column(BigInteger, primary_key=True)
# ... skipped ...
item_id = Column('item', BigInteger, ForeignKey('item.id'))
item = relationship('Item', backref='auctions')
我从这里得到了以下错误:
sqlalchemy.exc.InvalidRequestError
InvalidRequestError: When initializing mapper Mapper|Auction|auction, expression
'Item' failed to locate a name ("name 'Item' is not defined"). If this is a
class name, consider adding this relationship() to the Auction class after
both dependent classes have been defined.
我不明白为什么Python找不到Item这个类,即使我传递的是类本身,而不是用字符串传类名,我还是会遇到同样的错误。我一直在努力寻找如何用SQLAlchemy做简单关系的例子,如果这里有什么明显的问题,我表示抱歉。
10 个回答
22
SQLAlchemy的文档中关于导入所有SQLAlchemy模型提到:
不过,由于SQLAlchemy的“声明性”配置模式的特性,所有包含活跃SQLAlchemy模型的模块必须在使用这些模型之前先被导入。所以,如果你使用的是带有声明性基础的模型类,你需要想办法把所有模型模块都导入,这样才能在你的应用中使用它们。
一旦我导入了所有的模型(和它们之间的关系),关于找不到类名的错误就解决了。
- 注意:我的应用并没有使用Pyramid,但同样的原则也适用。
26
如果这是一个子包的类,就在这个子包的__init__.py
文件里添加Item
和Auction
类。
44
这一切问题的根源在于我在Pyramid中设置SQLAlchemy的方式。简单来说,你需要严格按照这一部分来操作,并确保每个模型都使用相同的declarative_base
实例作为基类。
我还没有将数据库引擎绑定到我的DBSession
上,这在你尝试访问表的元数据时会出现问题,尤其是在使用关系的时候。