尝试实例化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
答案 0 :(得分:12)
定义FK包括架构:dbo.tbConsumerAdviceCategories.ID_ConsumerAdviceCategories
答案 1 :(得分:6)
我也遇到了这个错误。在我的情况下,根本原因是我试图定义不同的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
。显然,类必须从相同的Base类派生才能相互了解。
希望这有助于某人。
答案 2 :(得分:1)
我没有解决我的问题,我不得不使用。
ConsumerAdviceCategory_ID = Column(INTEGER,
ForeignKey('tbConsumerAdviceCategories.ID_ConsumerAdviceCategories',
schema='dbo'))