首页 > 解决方案 > 避免在不同包中声明的表的 NoReferencedTableError

问题描述

我在不同的包中声明了模型,如下所示:

base.models.py

class BaseModel(object):

    __abstract__ = True

    id = sa.Column(sa.Integer, primary_key=True)

MyBase = declarative.declarative_base(cls=BaseModel, metadata=metadata)

foo.models.py

class FooModel(MyBase):                                                                                                                                                                                                                                        

    __tablename__ = 'foos' 

    leads = sa.orm.relationship('bar.models.Bar', backref='foo')

bar.models.py

class Bar(MyBase):                                                                                                                                                        

    __tablename__ = 'bars'

    foo_id = sa.Column(sa.Integer, sa.ForeignKey('foos.id'))

如果我查询Bar

count = session.query(Bar).filter_by(some_attr='spam').count()

Sqlalchemy 引发异常:

NoReferencedTableError: Foreign key associated with column 'bars.foo_id' could not find table 'foos' with which to generate a foreign key to target column 'id'

我可以通过导入Foo执行查询的模块来解决这个问题。

有没有办法配置模型以便不会发生此异常,并且我不必添加多余的导入?

sqlalchemy==1.2.5

标签: pythonpython-2.7sqlalchemy

解决方案


推荐阅读