问题
Getting this error when I try to instantiate the ConsumerAdvice class.
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
回答1:
Define the FK including schema: dbo.tbConsumerAdviceCategories.ID_ConsumerAdviceCategories
回答2:
I also hit this error. In my case the root cause was that I attempted to define different sqlalchemy base classes:
Base1 = declarative_base(cls=MyBase1)
Base1.query = db_session.query_property()
Base2 = declarative_base(cls=MyBase2)
Base2.query = db_session.query_property()
I had a ForeignKey relationship from one class that derives from Base1 to another class that derives from Base2. This didn't work -- I got a similar NoReferencedTableError. Apparently classes must derive from the same Base class in order to know about each other.
Hope this helps someone.
回答3:
That didn't solve my problem, I had to use.
ConsumerAdviceCategory_ID = Column(INTEGER,
ForeignKey('tbConsumerAdviceCategories.ID_ConsumerAdviceCategories',
schema='dbo'))
来源:https://stackoverflow.com/questions/7565549/sqlalchemy-foreignkey-cant-find-table