Add imported classes to metadata

2019-07-30 01:51发布

问题:

All,

I'm importing a group of classes for sqlalchemy from a separate file. They define the tables on my DB (inheriting from declarative_base()), and were originally located in the same file as my engine and metadata creation.

Since I have quite a few tables, and each of them is complex, I don't want them located in the same file I'm using them in. It makes working in the file more unwieldy, and I want a more clear delineation, since the classes document the current schema.

I refactored them to their own file, and suddenly the metadata does not find them automatically. Following this link, I found that it was because my main file declares base:

from tables import address, statements
Base = declarative_base()
metadata = MetaData()
Base.metadata.create_all()

And so does my tables file:

Base = declarative_base()
class address(Base):
    ...

So, as far as I can tell they get separate "bases" which is why the metadata can't find and create the declared tables. I've done some googling and it looks like this should be possible, but there isn't any obvious way to go about it.

How do I import tables defined in a separate file?

Update:

I tried this, and it sort of functions.

In the tables file, declare a Base for the table classes to import:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

Then in the main file, import the preexisting base and give its metadata to a new Base:

from sqlalchemy.ext.declarative import declarative_base
from tables import Base as tableBase
Base = declarative_base(metadata=tableBase.metadata)

After some more testing, I've found this approach leaves out important information. I've gone back to one file with everything in it, since that does work correctly. I'll leave the question open in case someone can come up with an answer that does work correctly. Or alternatively, point to the appropriate docs.