4

I have declared multiple orm classes in a.py:

Base = declarative_base()


class Message(Base):
    __tablename__ = "message"
    __table_args__ = {"schema": "stocktwits"}

    id = Column(BigInteger, primary_key=True)
    user_id = Column(BigInteger, nullable=False)
    body = Column(String, nullable=False)
    created_at = Column(DateTime, nullable=False)
    __table_args__ = (
        Index("created_at_idx", created_at),
    )
...

I am initializing the database in another file b.py:

def init_db(self):
    engine = create_engine(db_url)
    meta.create_all(engine)
    session = sessionmaker(bind=engine)()

I have two questions about such structure:

First, how can I refer to my orm objects declared in a.py when I call the method meta.create_all(engine) in b.py? Should I use Base.metadata.create_all(bind=engine)? In that case I have to figure out a way to share the Base object across files.

Second, I have read posts about importing objects before calling the meta.create_all() , since python does not allowed wildcard import within a function, does it mean I have to import all my orm objects individually, like from a.py import a, b, c, d, ....

chaos
  • 338
  • 4
  • 16

1 Answers1

4

Should I use Base.metadata.create_all(bind=engine)?

Yes - all model classes that inherit from Base are registered in its metadata, so calling Base.metadata.create_all(engine) will create all the associated tables.

In that case I have to figure out a way to share the Base object across files

from a import Base

in b.py should be sufficient. Obviously you should only define Base once.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • If only I could have found this rare answer earlier! Wasted more than a day, looking for an idea! Otherwise, I was defining Base() in all my files. I blame the documentation, as I could not find such hint there. – Am_I_Helpful Jun 28 '22 at 21:12