没有主键时左连接(如果可能,将胶水2给定一个查询)

时间:2012-12-28 13:40:25

标签: python sqlalchemy

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

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,但是玩家可以在任何联盟之外,alliances_id可以为null)。

1 个答案:

答案 0 :(得分: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')