7

如何使用 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'}]

为此,我需要内部加入。如何使它工作?

4

1 回答 1

8

为此,您首先需要有 asession来制作Query. relationship此外,在您的 MessageModel 上添加一个会很方便。

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})

可能有更优雅的方法来处理您的数据结构,但这个应该可以工作。

于 2012-11-27T15:18:20.803 回答