Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask SqlAlchemy join two models without foreign key MYSQL

I am joining two models without a 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 a FROM clause to join from. Tried joining to but got: Can't find any foreign key relationships between 'TimeOff' and 'Users'.

I dont have a foreign key defined in table

like image 766
user719852 Avatar asked Jun 11 '15 21:06

user719852


People also ask

How do I connect Flask with mysql database using SQLAlchemy?

After configuring SQLAlchemy by setting a database URI and disabling tracking, you create a database object using the SQLAlchemy class, passing the application instance to connect your Flask application with SQLAlchemy. You store your database object in a variable called db .

How do I join two tables in a Flask-SQLAlchemy?

How do I join two tables in Sqlalchemy? Python Flask and SQLAlchemy ORM Now we use the join() and outerjoin() methods. The join() method returns a join object from one table object to another. For example, following use of join() method will automatically result in join based on the foreign key.

Does SQLAlchemy require primary key?

The SQLAlchemy ORM, in order to map to a particular table, needs there to be at least one column denoted as a primary key column; multiple-column, i.e. composite, primary keys are of course entirely feasible as well.


1 Answers

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)
like image 108
Matt Healy Avatar answered Oct 03 '22 11:10

Matt Healy