【问题标题】:How do I correct this sqlalchemy.exc.NoForeignKeysError?如何更正此 sqlalchemy.exc.NoForeignKeysError?
【发布时间】:2019-06-01 12:59:14
【问题描述】:

为什么我会得到 TraceBack

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition
between parent/child tables on relationship County.Legislators - 
there are no foreign keys linking these tables.

Ensure that referencing columns are associated with a
ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

具有以下型号:

class County(Base):
    __tablename__ = 'tblCounty'
    CountyCode = Column('CountyCode', String, primary_key=True)
    Legislators = relationship('Legislators', backref='County', lazy='dynamic')

class Legislators(Base):
    __tablename__ = 'VLegislators'
    EmployeeNo = Column('EmployeeNo', String, primary_key=True)
    CountyCode = Column('CountyCode', String, ForeignKey('County.CountyCode'))

我正在尝试映射由新罕布什尔州提供的面向公众的 MS SQL 数据库。因此不允许架构更改。

为什么在 Class Legislators 中明确定义了 ForeignKey 关系时却抱怨缺少 ForeignKey?

【问题讨论】:

  • 这个错误完全是关于设置ORM;在这个阶段(或实际上任何阶段)SQLA 既不知道也不关心数据库中的物理 FK 是什么
  • 请注意,由于您明确提供了列名,因此您可以使用像 country_code 这样的属性名称,在 Python 中作为属性更自然地阅读

标签: python sqlalchemy


【解决方案1】:

AFAIK 你应该在 ForeignKey 中使用表名:

CountyCode = Column('CountyCode', String, ForeignKey('tblCounty.CountyCode'))

【讨论】:

  • 成功了!谢谢。
  • 或者,为了减少混淆,在可以避免的情况下不要使用字符串:ForeignKey(County.CountyCode)
  • 原来这也解决了大部分错误 - 非常感谢这个提示!!!
猜你喜欢
  • 1970-01-01
  • 2021-07-18
  • 2019-12-05
  • 2017-12-10
  • 2013-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-18
相关资源
最近更新 更多