简化后,我有以下类结构(在单个文件中):
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建立简单关系的例子,所以如果这里有明显的错误,我道歉。
如果是子包类,则将
Item
和Auction
类添加到子包中的__init__.py
。另外,即使这不适用于OP,对于任何在这里登陆的人,如果遇到同样的错误,请检查确保您的表名中没有破折号。
例如,一个名为“movie genres”的表,然后用作SQLAlchemy关系中的辅助表,将生成相同的错误
"name 'movie' is not defined"
,因为它只读取到短划线。切换到下划线(而不是破折号)可以解决问题。这一切都是因为我在金字塔中设置了SQLAlchemy。实际上,您需要紧跟this section的字母,并确保使用与每个模型的基类相同的
declarative_base
实例。我也没有将数据库引擎绑定到我的
DBSession
上,这在您尝试访问表元数据之前不会让您感到困扰,这种情况在您使用关系时会发生。相关问题 更多 >
编程相关推荐