Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query pre-existing table from SQlAlchemy ORM session?

I'm using SQLAlchemy to do some data processing and create some tables. I'm loading data from an table orm_table defined with the Declarative Base class ORMTable, so can query the database with the session.query(ORMTable).all() statement.

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?

like image 621
sfactor Avatar asked Dec 05 '16 04:12

sfactor


People also ask

How do I see all tables in SQLAlchemy?

The best way is to use inspect : Create the inspector and connect it to the engine. Collect the names of tables within the database.

How does the querying work with SQLAlchemy?

All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.

How do you update existing table rows in SQLAlchemy in Python?

Update table elements in SQLAlchemy. Get the books to table from the Metadata object initialized while connecting to the database. Pass the update query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.


1 Answers

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.

like image 81
ichbinblau Avatar answered Nov 16 '22 23:11

ichbinblau