我有一个Player
课程,每个玩家拥有X个Character
个实例:
class Player(Model):
characters = relationship('Character', back_populates='owner')
class Character(Model):
owner = relationship('Player', back_populates='characters')
owner_id = Column('player_id', Integer, ForeignKey('player.id'))
但除此之外,每个人都有一个他正在控制的角色。这意味着每个玩家拥有他们拥有的多个角色,但其中只有一个是活跃的,所以我需要能够将其保存在一个单独的值左右。
如何在现有的一对多关系旁边添加一对一关系?
答案 0 :(得分:0)
如果您向Player表添加一列,以保持玩家当前角色,该怎么办?您可以在需要时进行更改:
class Player(Model):
characters = relationship('Character', back_populates='owner')
current_character = Column('character_id', Integer, ForeignKey('character.id'))
def refresh(self, id):
c_id = session.query(Character).filter(character.id == id)
if c_id:
self.current_character = c_id.id
session.add(self)
答案 1 :(得分:0)
显然SQLAlchemy对uselist=False
有一个relationship()
选项,我最后才使用它......
class Player(Model):
character = relationship('Character', uselist=False, back_populates='owner')
characters = relationship('Character', back_populates='owner')
class Character(Model):
owner = relationship('Player', back_populates='characters')
owner_id = Column('player_id', Integer, ForeignKey('player.id'))