Flask SqlAlchemy join two models without foreign key MYSQL Flask SqlAlchemy join two models without foreign key MYSQL mysql mysql

Flask SqlAlchemy join two models without foreign key MYSQL


You need to tell SQLAlchemy how to join the tables. Try something like this:

result = db.session.query(Users).join(TimeOff,Users.userName==TimeOff.userName)


To improve upon @Matt Healy's answer, if you also want to be able to access attributes on the joined object you can do something like:

user, timeOff = db.session.query(Users, TimeOff).join(    TimeOff, Users.userName == TimeOff.userName).first()

Then timeOff.dayWork etc. will give the information you need.


Its an old post but I had a similar problem

result = session.query(models.Users).join(models.TimeOff, models.Users.userName == models.TimeOff.userName).all()

with this method, I can reach the features of the first object which is Users but not the TimeOff. I am wondering if it is possible to reach the secondary object's attributes. But I hope this helps.