0

在游戏中有两个简单的实体 Player 和 Alliance,我需要使用联盟名称获取同一国家的所有用户(如果他们在任何联盟中获取名称,否则联盟名称为空)。

class Base(object):
     def __tablename__(self):
       return self.__name__.lower()

     id = Column(Integer, primary_key=True, nullable=False)

class PlayerModel(Base):
    __tablename__ = 'players'
    alliances_id = Column(Integer, nullable=True)
    username = Column(String(30), nullable=False)
    nation = Column(String(20), nullable=False)
    score = Column(String(20), default=0)

class AllianceModel(Base):
    __tablename__ = 'alliances'
    name = Column(String(50), nullable=False)
    nation = Column(String(20), nullable=False)


//query

for player in session.query(PlayerModel).filter(PlayerModel.nation.like(nation)):
    alliance =session.query(AllianceModel).filter(AllianceModel.id==player.alliance_id).first()
    result.append({'username':player.username, 'alliance':alliance.name})

我可以将其仅连接到一个查询吗?(我知道当有外键时使用 join,但玩家可以不在任何联盟中,alions_id 可以为空)。

4

1 回答 1

1

将列标记alliances_id为外键:

from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship

class PlayerModel(Base):
    __tablename__ = 'players'
    alliances_id = Column(Integer, nullable=True, ForeignKey('AllianceModel.id'))
    alliance = relationship('AllianceModel')
    username = Column(String(30), nullable=False)
    nation = Column(String(20), nullable=False)
    score = Column(String(20), default=0)

然后简单参考player.alliance

for player in session.query(PlayerModel).filter(PlayerModel.nation.like(nation)):
    result.append({'username':player.username, 'alliance': player.aliance.name if player.aliance is not None else ''})

如果您不愿意或无法将ForeignKey()约束添加到alliances_id,您还可以将该信息添加到relationship()声明中:

    alliances_id = Column(Integer, nullable=True)
    alliance = relationship('AllianceModel', foreign_keys='AllianceModel.id')
于 2012-12-28T13:51:02.023 回答