我正在使用 SQLAlchemy 进行一些数据处理并创建一些表。我正在从使用 Declarative Base
类 ORMTable
定义的表 orm_table
加载数据,因此可以使用 session 查询数据库。 query(ORMTable).all()
语句。
但是,我还需要查询另一个表non_orm_table
,这个表已经存在于数据库中,没有在orm中定义。如何从同一 session 中查询此表?我没有与之关联的类,所以想知道这种情况的标准做法是什么?
最佳答案
这是实现它的代码片段:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('<db_connection_string>', echo=True)
Base = declarative_base(engine)
class NonOrmTable(Base):
"""
eg. fields: id, title
"""
__tablename__ = 'non_orm_table'
__table_args__ = {'autoload': True}
def loadSession():
""""""
metadata = Base.metadata
Session = sessionmaker(bind=engine)
session = Session()
return session
if __name__ == "__main__":
session = loadSession()
res = session.query(NonOrmTable).all()
print res[1].title
关键是使用 SqlAlchemy 的 autoload
属性。它将现有表字段名称动态映射到类。
希望对你有帮助。
关于python - 如何从 SQlAlchemy ORM session 中查询预先存在的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40966952/