【问题标题】:SQLAlchemy ForeignKey can't find tableSQLAlchemy ForeignKey 找不到表
【发布时间】:2011-11-25 19:18:28
【问题描述】:

当我尝试实例化 ConsumerAdvice 类时出现此错误。

Foreign key associated with column 'tbConsumerAdvice.ConsumerAdviceCategory_ID' 
could not find table 'tbConsumerAdviceCategories' with which to generate a
foreign key to target column 'ID_ConsumerAdviceCategories'
class ConsumerAdviceCategory(Base):
    __tablename__ = 'tbConsumerAdviceCategories'
    __table_args__ = {'schema':'dbo'}
    ID_ConsumerAdviceCategories = Column(INTEGER, Sequence('idcac'),\
            primary_key=True)
    Name = Column(VARCHAR(50), nullable=False)

    def __init__(self,Name):
        self.Name = Name

    def __repr__(self):
        return "< ConsumerAdviceCategory ('%s') >" % self.Name

class ConsumerAdvice(Base):
    __tablename__ = 'tbConsumerAdvice'
    __table_args__ = {'schema':'dbo'}
    ID_ConsumerAdvice = Column(INTEGER, Sequence('idconsumeradvice'),\
            primary_key=True)
    ConsumerAdviceCategory_ID = Column(INTEGER,\
            ForeignKey('tbConsumerAdviceCategories.ID_ConsumerAdviceCategories'))
    Name = Column(VARCHAR(50), nullable=False)
    Category_SubID = Column(INTEGER)

    ConsumerAdviceCategory = relationship("ConsumerAdviceCategory",\
            backref=backref('ConsumerAdvices'))

    def __init__(self,Name):
        self.Name = Name

    def __repr__(self):
        return "< ConsumerAdvice ('%s') >" % self.Name

【问题讨论】:

  • 不知道为什么,但是如果您从__table_args__ 中删除schema,它可以工作(用SQLite 测试)。您使用哪种 RDBMS?
  • ... 尝试定义 FK 包括架构:dbo.tbConsumerAdviceCategories.ID_ConsumerAdviceCategories
  • @van 这是 MSSQL,将架构添加到 FK 定义中有效!很多 KUDOS.. 你可以添加答案,以便我可以将其标记为已回答?

标签: python foreign-keys sqlalchemy


【解决方案1】:

定义 FK,包括架构:dbo.tbConsumerAdviceCategories.ID_ConsumerAdviceCategories

【讨论】:

    【解决方案2】:

    我也遇到了这个错误。就我而言,根本原因是我试图定义不同的 sqlalchemy 基类:

    Base1 = declarative_base(cls=MyBase1)
    Base1.query = db_session.query_property()
    
    Base2 = declarative_base(cls=MyBase2)
    Base2.query = db_session.query_property()
    

    我有一个ForeignKey 关系,从一个派生自Base1 的类到另一个派生自Base2 的类。这不起作用——我得到了一个类似的NoReferencedTableError。显然,类必须派生自同一个基类才能相互了解。

    希望这对某人有所帮助。

    【讨论】:

      【解决方案3】:

      这并没有解决我的问题,我不得不使用。

      ConsumerAdviceCategory_ID = Column(INTEGER,
                  ForeignKey('tbConsumerAdviceCategories.ID_ConsumerAdviceCategories',  
                  schema='dbo'))
      

      【讨论】:

      • 我不明白你是如何让它工作的,因为添加这样的参数会引发TypeError: Additional arguments should be named &lt;dialectname&gt;_&lt;argument&gt;
      猜你喜欢
      • 2020-10-24
      • 2021-08-16
      • 2019-11-05
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 2021-08-02
      相关资源
      最近更新 更多