How to query pre-existing table from SQlAlchemy ORM session?
Here is the code snippet to make it:
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
The key is to use SqlAlchemy’s autoload
attribute. It will map the existing table field names to the class dynamically.
I hope it helps.