Flask SqlAlchemy combines two models without MYSQL foreign key

I am concatenating two models with no foreign key:

Models:

class Users(db.Model):
    __tablename__ = "Users"
    userName = db.Column(db.String, primary_key=True)
    lastLogin = db.Column(db.DateTime)

class TimeOff
    __tablename__ = "timeOff"
    timeOffID = db.Column(db.Integer, primary_key=True)
    userName = db.Column("userName", db.String,   db.ForeignKey('appUsers.userName')),
    dayWork = db.Column(db.DateTime)

      

View:

result = db.session.query(models.Users).join(models.TimeOff)

      

sqlalchemy.exc.InvalidRequestError: Could not find FROM clause to join. Tried joining but got: Can't find any external relationship between "TimeOff" and "Users".

I have no foreign key defined in the table

+6


source to share


2 answers


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



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

      

+9


source


To improve on @Matt Healy's answer, if you also want to be able to access the attributes of the merged 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 provide the information you need.

0


source







All Articles