SQLAlchemy ForeignKey can't find table

2019-04-20 04:43发布

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

3条回答
劳资没心,怎么记你
2楼-- · 2019-04-20 05:06

That didn't solve my problem, I had to use.

ConsumerAdviceCategory_ID = Column(INTEGER,
            ForeignKey('tbConsumerAdviceCategories.ID_ConsumerAdviceCategories',  
            schema='dbo'))
查看更多
我只想做你的唯一
3楼-- · 2019-04-20 05:14

Define the FK including schema: dbo.tbConsumerAdviceCategories.ID_ConsumerAdviceCategories

查看更多
beautiful°
4楼-- · 2019-04-20 05:16

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.

查看更多
登录 后发表回答