SqlAlchemy:动态查询

2024-06-23 02:54:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

例如,我需要从链接“organization”、“people”、“staff”三个表的列表(表名、列名、连接列)生成查询。我怎样才能做好呢?在

例如,我的意思是这个列表: [{'table':'organization','column':'staff'u id'}, {'table':'staff','column':'id'}]

例如,输出可以包含: 组织.id, 组织名称, 组织工作人员, 职员.id, 职员姓名 (name column只在输出中显示,因为我需要一个简单的示例,接收表的所有列,而array必须只设置连接)


Tags: 代码名称id数据库列表参数sqlalchemy链接
2条回答

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

虽然还没有测试,但使用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)

相关问题 更多 >