sfa*_*tor 7 python orm sqlalchemy
我正在使用 SQLAlchemy 进行一些数据处理并创建一些表。我正在从orm_table使用Declarative Baseclass定义的表加载数据ORMTable,因此可以使用session.query(ORMTable).all()语句查询数据库。
但是,我还需要查询non_orm_table数据库中已存在且未在 orm 中定义的另一个表。如何从同一会话中查询此表?我没有与之相关的课程,所以想知道这种情况的标准做法是什么?
这是实现它的代码片段:
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
Run Code Online (Sandbox Code Playgroud)
关键是使用SqlAlchemy’s autoload属性。它将现有的表字段名称动态映射到类。
我希望它有帮助。
| 归档时间: |
|
| 查看次数: |
5700 次 |
| 最近记录: |