2011-09-07 126 views
1

如何在SqlAlchemy ORM中進行動態查詢(如果它是一個正確的名稱)。SqlAlchemy:動態查詢

我用SqlAlchemy作爲數據庫的抽象,用python代碼查詢,但是如果我需要動態生成這些查詢,不僅設置查詢參數如「id」?

例如,我需要從列表(表名,列名,連接列)生成鏈接三個表,如「組織」,「人員」,「職員」的查詢。我如何正確地做到這一點?

例如,我的意思是這個列表: [{'table':'organization','column':'staff_id'}, {'table':'staff','column':'id'} ]

和輸出例如可以包含: organisation.id,organisation.name,organisation.staff_id,staff.id,staff.name (名稱列僅呈現輸出,因爲我需要簡單的例子,recieving所有表的列和數組必須只設置連接)

+0

「我需要從」str「元素(表名,列名,連接列)數組中生成查詢」。這沒有什麼意義。請舉一個例子。 –

+1

嗯..你已經向我們展示了* input *,但它可能會有助於向我們展示預期的輸出,無論是等價的sqlalchemy語句還是生成的SQL。我可以想出幾種解釋你的意見的方式,每種方式的意思都不一樣。 – SingleNegationElimination

+0

「我的意思是這個數組」...不是一個數組。這是一個字典列表。 –

回答

1

sqlalchemy.sql.join和/或sqlalchemy.select的調用結果,您可以使用mapper。這大致相當於在數據庫視圖上使用mapper;您可以自然地查詢這些類,但不一定會創建新記錄。您還可以使用sqlalchemy.orm.column_property將計算值映射到對象屬性。當我讀到你的問題時,這三種技術的組合應該滿足你的需求。

1

還沒有測試過,但它與SQLAlchemy的ORM,你可以鏈接在一起,如:

from sqlalchemy import create_engine, Integer, String 
from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy import Column, ForeignKey 
from sqlalchemy.orm import relationship 
from asgportal.database import Session 

Engine = create_engine('mysql+mysqldb://user:[email protected]:3306/mydatabase', pool_recycle=3600) 
Base = declarative_base(bind=Engine) 
session = Session() 
session.configure(bind=Engine) 

class DBOrganization(Base): 
    __tablename__ = 'table_organization' 
    id = Column(Integer(), primary_key=True) 
    name = Column(ASGType.sa(ASGType.STRING)) 

class DBEmployee(Base): 
    __tablename__ = 'table_employee' 
    id = Column(Integer(), primary_key=True) 
    name = Column(String(255)) 

    organization_id = Column(Integer(), ForeignKey('table_organization.id')) 
    # backref below will be an array[] unless you specify uselist=False 
    organization = relationship(DBOrganization, backref='employees') 

Base.metadata.create_all() 

# From here, you can query: 
rs = session.query(DBEmployee).join(DBEmployee.organization).filter(DBOrganization.name=='my organization') 

for employees in rs: 
    print '{0} works for {1}'.format(employees.name,employees.organization.name)