2015-06-11 61 views
3

我沒有一個外鍵連接兩個型號:瓶SQLAlchemy中加入兩種型號不用擔心外鍵MYSQL

型號:

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) 

查看:

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'.

我沒有在表

中定義的外鍵

回答

5

您需要告訴SQLAlchemy如何連接表。嘗試這樣的:

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

這是不相關的表的聯接? – roy

+0

這適用於不相關的表格。確保運行時填充表格。花了我一會兒才發現我沒有結果,因爲我的桌子沒有人口。 – Kevin