2017-03-29 193 views
1

我已經反映了現有的數據庫並覆蓋了一些列。 有人能告訴我什麼是錯的以下?SQLAlchemy關係沒有外鍵

metadata = MetaData(engine) 
class User(Base): 
    __tablename__ = 'users' 
    __table__ = Table('dim_user', metadata, 
         Column('user_id', Integer, primary_key=True), 
         autoload=True) 
    projects = relationship('Project', back_populates='users') 

class Project(Base): 
    __tablename__ = 'projects' 
    __table__ = Table('dim_project', metadata, 
         Column('project_id', Integer, primary_key=True), 
         Column('user_id', Integer, ForeignKey('users.user_id')), 
         autoload=True) 

當我試圖查詢任何東西,我得到:

NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.projects - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression. 
+0

您明確地將聲明性模型傳遞給一個用於['__table__']的表格(http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/table_config.html#using-a-hybrid-一般來說,重寫'__tablename__'和'Table'結構。顯式表的名稱爲'dim_user'。然後嘗試引用'Project'中的'users.user_id',但該表不存在於元數據中,因爲沒有創建這樣的表。 –

回答

0

正如@ ILJA-everilä已經嘗試過在他的評論中傳達,你的模型是不是consitent:你明確地定義__table__屬性,覆蓋然後__tablename__屬性 - 你必須找出其中是正確的。在你的ForeignKey定義中,你可以參考__tablename__User而不是__table__的定義。

User.projectsrelationship定義不明確地提及一個ForeigKey也不是連接條件,因爲你的元數據被搞砸了(見上文)的SQLAlchemy無法自動您想要的決定。