简体   繁体   English

如何从 SQlAlchemy ORM 会话查询预先存在的表?

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

I'm using SQLAlchemy to do some data processing and create some tables.我正在使用 SQLAlchemy 进行一些数据处理并创建一些表。 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.我加载数据从表orm_table与定义的Declarative BaseORMTable ,所以可以查询与数据库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.但是,我还需要查询数据库中已存在且未在orm中定义的另一个表non_orm_table 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?我没有与之相关的课程,所以想知道这种情况的标准做法是什么?

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.关键是要使用SqlAlchemy's autoload属性。 It will map the existing table field names to the class dynamically.它将现有的表字段名称动态映射到类。

I hope it helps.我希望它有帮助。

You can also do it as below.您也可以按照以下方式进行。

  #Considering account is your table and first_name is a column

  from sqlalchemy import create_engine, select, MetaData, Table

  CONN = create_engine('postgresql+psycopg2://username:password@localhost:5432/dbname', 
  client_encoding="UTF-8") 
  META_DATA = MetaData(bind=CONN, reflect=True)
  account = META_DATA.tables['account']
  stmt = select([account]).where(account.columns.first_name == 'Michael')
  connection = CONN.connect()
  results = connection.execute(stmt).fetchall()

  # to print the result
  for result in results:
      print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM