簡體   English   中英

如何從 SQlAlchemy ORM 會話查詢預先存在的表?

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

我正在使用 SQLAlchemy 進行一些數據處理並創建一些表。 我加載數據從表orm_table與定義的Declarative BaseORMTable ,所以可以查詢與數據庫session.query(ORMTable).all()語句。

但是,我還需要查詢數據庫中已存在且未在orm中定義的另一個表non_orm_table 如何從同一會話中查詢此表? 我沒有與之相關的課程,所以想知道這種情況的標准做法是什么?

這是實現它的代碼片段:

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

關鍵是要使用SqlAlchemy's autoload屬性。 它將現有的表字段名稱動態映射到類。

我希望它有幫助。

您也可以按照以下方式進行。

  #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