pythonormsqlalchemy

How to query a pre-existing table in SQLAlchemy ORM?


I'm using SQLAlchemy to do some data processing and create some tables.

I'm loading data from a table orm_table defined by the class ORMTable (which inherits from a Base class which itself inherits from a DeclarativeBase class), so I can query that table using session.query(ORMTable).all().

However, I also need to query another table non_orm_table that already exists in the database and is not defined in the orm.

How do I query this table from within the same session? I don't have a class associated with it so wondering what is the standard practice for such cases?


Solution

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