I have a following directory structure.
├── alchemy_models
│ ├── foo.py
│ ├── bar.py
│ └── __init__.py # Base in here
└── setup.py
foo.py
class Foo(Base):
__tablename__ = 'foos'
__table_args__ = {'schema': 'foo'}
barid = Column(Integer, ForeignKey('bar.bars.id'))
bar.py
class Bar(Base):
__tablename__ = 'bars'
__table_args__ = {'schema': 'bar'}
id = Column(Integer, primary_key=True)
If I would then have some file like main.py
where
engine = create_engine('sqlite://')
engine.execute('attach ":memory:" as "bar"')
engine.execute('attach ":memory:" as "foo"')
Base.metadata.create_all()
This would fail with Foreign key associated with column 'foo.barid' could not find table 'bar.bars'...
Which probably happens because no one imported bar.py
and so bar table isn't in metadata.
But what to do about it? We can from bar import Bar
inside foo.py
but this can lead to circular import problem in a general case.
Right now we have list of all "schema" files in init.py and import all of them one by one before using any of them in main.py
, but that's seems like a workaround solution.
How to do that properly?