How to achieve inner join using SQLAlchemy ? I am trying to make simple chat
class Base(object):
def __tablename__(self):
return self.__name__.l
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.