SqlAlchemy:动态查询

时间:2011-09-07 16:01:10

标签: python database orm sqlalchemy

如何在SqlAlchemy ORM中进行动态查询(如果它们是正确的名称)。

我使用SqlAlchemy作为数据库的抽象,在python代码中使用查询,但是如果我需要动态生成这些查询,而不仅仅像“id”那样设置查询参数呢?

例如,我需要从列表(表名,列名,连接列)生成查询,这些查询链接三个表,如“组织”,“人员”,“员工”。我该怎么做呢?

例如,我的意思是这个清单:   [{'table':'organization','column':'staff_id'},   {'table':'staff','column':'id'}]

例如输出可能包含:   organisation.id,organisation.name,organisation.staff_id,staff.id,staff.name (name列仅出现在输出中,因为我需要简单的示例,接收表的所有列,并且数组必须只设置连接)

2 个答案:

答案 0 :(得分: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:password@localhost: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)

答案 1 :(得分:1)

您可以对sqlalchemy.sql.join和/或sqlalchemy.select的调用结果使用mapper。这大致相当于在数据库视图中使用mapper;您可以自然地查询这些类,但不一定要创建新记录。您还可以使用sqlalchemy.orm.column_property将计算值映射到对象属性。当我读到你的问题时,这三种技术的结合应该可以满足你的需求。

相关问题