【问题标题】:SqlAlchemy: dynamic queriesSqlAlchemy:动态查询
【发布时间】:2011-09-07 16:01:10
【问题描述】:

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

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

例如,我需要从链接三个表(如“组织”、“人员”、“员工”)的列表(表名、列名、连接列)生成查询。我怎样才能正确地做到这一点?

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

例如,输出可能包含: 组织 ID、组织名称、组织人员 ID、人员 ID、人员名称 (名称列仅在输出中显示,因为我需要简单的示例,接收表的所有列,并且数组必须设置连接)

【问题讨论】:

  • “我需要从“str”元素数组(表名、列名、连接列)生成查询”。这没有多大意义。请举个例子。
  • Hmm.. 您已经向我们展示了 输入,但是向我们展示预期的输出可能会有所帮助,无论是在等效的 sqlalchemy 语句还是生成的 SQL 方面.我能想到几种解释您输入的方法,每一种都有非常不同的含义。
  • "我的意思是这个数组"...不是数组。这是一个字典列表。

标签: python database orm sqlalchemy


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    尚未测试,但它使用 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)
    

    【讨论】:

      猜你喜欢
      • 2013-04-02
      • 2019-07-15
      • 1970-01-01
      • 2022-12-10
      • 2019-03-10
      • 2019-03-09
      • 2014-02-01
      • 2015-10-29
      • 1970-01-01
      相关资源
      最近更新 更多