Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy ForeignKey can't find table

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
like image 719
MFB Avatar asked Sep 27 '11 07:09

MFB


2 Answers

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.

like image 83
Shahaf Avatar answered Oct 11 '22 23:10

Shahaf


Define the FK including schema: dbo.tbConsumerAdviceCategories.ID_ConsumerAdviceCategories

like image 40
van Avatar answered Oct 11 '22 23:10

van