2017-03-29 195 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无法自动您想要的决定。