我有两张桌子,我正在尝试建立一对多的关系。应该有一个Player
个Sessions
。
import sqlalchemy as sql
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Session(Base):
__tablename__ = 'session'
id = sql.Column('session_id', sql.INTEGER, primary_key=True)
player_id = sql.Column(sql.INTEGER, sql.ForeignKey('player.player_id'))
class Player(Base):
__tablename__ = 'player'
id = sql.Column('player_id', sql.INTEGER, primary_key=True)
sessions = relationship('Session', backref='player')
但是,我在创建数据库时遇到的错误是
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize -
can't proceed with initialization of other mappers. Triggering mapper:
'Mapper|Player|player'. Original exception was: When initializing mapper
Mapper|Player|player, expression 'Session' failed to locate a name ("name
'Session' is not defined"). If this is a class name, consider adding this
relationship() to the <class 'analysis_db_tables.Player'> class after both
dependent classes have been defined.
我已尝试更改Player
和Session
的顺序,将relationship
行删除为Player
以外的
Player.sessions = relationship('Session', backref='player')
我也尝试在两个类中使用back_populates
和relationship
语句。我在这里做错了什么?
这个问题在构建我的数据库代码时似乎随机出现,我已经将表格配对到这两个,同时仍然重新创建问题。我正在使用SQLAlchemy和postgres。感谢。
答案 0 :(得分:0)
尝试:
sessions = sql.relationship('Session', backref='player')
而不是:
sessions = relationship('Session', backref='player')