簡體   English   中英

SQLAlchemy關系沒有外鍵

[英]SQLAlchemy Relationships No Foreign Key

我反映了一個現有的數據庫並覆蓋了一些列。 有人可以告訴我以下內容有什么問題嗎?

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.

作為@ ILJA-everilä已經嘗試過在他的評論中傳達,你的模型是不是consitent:你明確地定義__table__屬性,然后覆蓋__tablename__性-你必須找出其中的是正確的。 ForeignKey定義中,您引用的是User__tablename__ ,而不是__table__定義。

User.projectsrelationship定義中,您沒有顯式引用ForeigKeyForeigKey條件,並且由於元數據混亂(請參見上文),因此sqlalchemy無法自動確定所需的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM