<p>简化后,我有以下类结构(在单个文件中):</p>
<pre><code>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')
</code></pre>
<p>我由此得到以下错误:</p>
<pre><code>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.
</code></pre>
<p>我不确定Python是如何找不到Item类的,因为即使在传递类时,也会得到相同的错误,而不是将名称作为字符串。我一直在努力寻找如何与SQLAlchemy建立简单关系的例子,所以如果这里有明显的错误,我道歉。</p>
<p>另外,即使这不适用于OP,对于任何在这里登陆的人,如果遇到同样的错误,请检查确保您的表名中没有破折号。</p>
<p>例如,一个名为“movie genres”的表,然后用作SQLAlchemy关系中的辅助表,将生成相同的错误<code>"name 'movie' is not defined"</code>,因为它只读取到短划线。切换到下划线(而不是破折号)可以解决问题。</p>