9

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?

user1685095
  • 5,787
  • 9
  • 51
  • 100
  • At least in your example definition the schema name is `bar` *and* the table name is `bar` as well, so naturally it could not find `bar.bars...`. – Ilja Everilä Apr 24 '17 at 11:19
  • 1
    that's just a typo. I typed this example right here. – user1685095 Apr 24 '17 at 11:21
  • Ok, as for your thought on having to import `bar.Bar` in order to realize the `Table` generated by the declarative class, since if you don't import it the class definition is not evaluated, you are correct. Usually you'd handle it for example by importing the model definitions in the `__init__.py` of `alchemy_models`. – Ilja Everilä Apr 24 '17 at 11:23
  • THats the way I usually do it, have a `from foo import *` in the `__init__` file, that way sqlalchemy catches the table definitions – reptilicus Apr 24 '17 at 15:20
  • Meanwhile, I'm running into this now (cross-schema foreign keys) and can't get it to work. Ensuring all models are imported isn't helping – kevlarr Aug 11 '20 at 15:23

0 Answers0