如何使用SQLAlchemy实现内连接?

时间:2012-11-27 12:38:05

标签: python python-2.7 sqlalchemy

如何使用SQLAlchemy实现内连接? 我正在尝试进行简单的聊天

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

    id = Column(Integer, primary_key=True)

Base = declarative_base(cls=Base)

class PlayerModel(Base):
    __tablename__ = 'players'
    username = Column(String(30), nullable=False)
    email = Column(String(75), nullable=False)
    password = Column(String(128), nullable=False)

class MessageModel(Base):
    __tablename__ = 'messages'
    player_id = Column(Integer,ForeignKey('chats.id'), nullable=False)
    message = Column(String(2000), nullable=False)
    time = Column(TIMESTAMP, server_default=func.now())

    def __repr__(self):
        return "<Message('%s')>" % (self.type)

我想阅读所有比某个日期更年轻的消息,并且结果是要有像

这样的词典列表
[{'username':'x','message':'y','time':'number0'},{'username':'y','message':'z','time':'number1'},
{'username':'x','message':'zz','time':'number'}]

为此,我需要内部联接。如何使这个工作?

1 个答案:

答案 0 :(得分:7)

为此,首先需要session来制作Query。此外,在MessageModel上添加relationship可能很方便。

class MessageModel(Base):
    __tablename__ = 'messages'
    player_id = Column(Integer,ForeignKey('chats.id'), nullable=False)
    message = Column(String(2000), nullable=False)
    time = Column(TIMESTAMP, server_default=func.now())
    player = relationship(PlayerModel, backref="messages")

这将在两个模型上创建关系。

results = (session.query(PlayerModel)
                  .join(PlayerModel.messages)
                  .values(PlayerModel.username,
                          MessageModel.message,
                          MessageModel.time))
# results will be a generator object

# This seems a bit convoluted, but here you go.
resultlist = []
for username, message, time in results:
    resultlist.append({'message': message,
                       'username': username,
                       'time': time})

可能有更优雅的方式来实现您的数据结构,但这个方法应该有效。