python - 避免在不同包中声明的表的 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
解决方案
推荐阅读
- r - 如何使用 Shiny 中的 locator() 函数在绘图上绘制多边形?
- python - 在 Python 中进行裸 os.fork() 调用的充分理由是什么?
- javascript - 如何将 Math.round 放入函数并使用户输入受限?
- ios - 使用 CoreMotion 检测手机倾斜
- python - 为什么我不能把这两个框架放在一起
- laravel - 如何在 Laravel 中的数据透视表上存储值 | 多对多
- javascript - Discordjs messagecollector 选择特定频道
- python - Matplotlib 在不同部分绘制具有不同颜色的连续图
- r - 在 Highcharts R 中叠加正态分布
- c++ - 带有默认参数的包装方法,该参数是指向另一个包装类型的空指针