【发布时间】:2022-01-20 22:33:30
【问题描述】:
我在a.py中声明了多个orm类:
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),
)
...
我正在另一个文件b.py中初始化数据库:
def init_db(self):
engine = create_engine(db_url)
meta.create_all(engine)
session = sessionmaker(bind=engine)()
我对这种结构有两个问题:
首先,当我在b.py 中调用meta.create_all(engine) 方法时,如何引用我在a.py 中声明的orm 对象?我应该使用Base.metadata.create_all(bind=engine) 吗?在这种情况下,我必须想办法在文件之间共享Base 对象。
其次,我在调用 meta.create_all() 之前有 read posts about 导入对象,因为 python 不允许在函数中导入通配符,这是否意味着我必须单独导入所有 orm 对象,例如 from a.py import a, b, c, d, ....
【问题讨论】:
标签: python sqlalchemy