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?
The best way is to use inspect : Create the inspector and connect it to the engine. Collect the names of tables within the database.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With