Home > OS >  how to use create_all() for sqlalchemy orm objects across files
how to use create_all() for sqlalchemy orm objects across files

Time:12-18

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, ....

CodePudding user response:

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.

  • Related