How to achieve inner join using SQLAlchemy?

后端 未结 1 1441
慢半拍i
慢半拍i 2021-01-05 10:56

How to achieve inner join using SQLAlchemy ? I am trying to make simple chat

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


        
相关标签:
1条回答
  • 2021-01-05 11:17

    For that you first need to have a session to make a Query. Additionally it can be convenient to have a relationship on your 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")
    

    This will create the relationship on both models.

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

    There may be more elegant ways to come to your data structure but this one should work.

    0 讨论(0)
提交回复
热议问题