【问题标题】:selecting whole entities from SQLAlchemy subqueries从 SQLAlchemy 子查询中选择整个实体
【发布时间】:2014-10-15 15:00:39
【问题描述】:

如果我在 SQLAlchemy 查询中指定映射类(~= 数据库表),则返回的行将包含这些类的实例:

q = sess.query(table1, table2, table3.string_column)
q.first()
==> ( <instance of table1>,
      <instance of table2>,
      'string' )

但是,如果我从子查询中选择,则返回的行包含单个列而不是类实例:

q = sess.query(table1, table2, table3.string_column)

q2 = sess.query( q.subquery() )
q2.first()
==> ( col1_of_table1, col2_of_table1, ...,
      col2_of_table2, col2_of_table2, ...,
      'string' )

有没有办法指定我想将子查询中的行保留为映射类的实例?

如果不加入映射类的新实例,我无法弄清楚如何做到这一点。 corresponding_column 方法允许我从子查询中引用特定的,但我不知道如何从子查询中引用完整的实体。我尝试过使用select_from,但它并没有给我正确的行为。

有什么建议吗?

【问题讨论】:

    标签: python-2.7 sqlalchemy


    【解决方案1】:

    返回实体的查询总是需要被告知那些实体——这就是它想要“选择”的东西。行的来源是它想要“从”中选择的内容。两个不同的东西。

    给定的:

    q = sess.query(table1, table2, table3.string_column)
    q = q.subquery()
    

    一旦你调用了 subquery(),查询的 ORM 特性就基本消失了,它只是一个 SELECT 对象。要从中选择实体,您必须再次命名它们,并使用 select_entity_from (如果您实际上在 0.7 上,那就是 select_from() 那时的情况;您需要具体说明“不是正确的行为):

    q2 = sess.query(table1, table2, table3.string_column).select_entity_from(q)
    

    【讨论】:

    • 喜欢“ORM-ness”这个词
    【解决方案2】:

    根据Selecting Entities from Subqueries,可以使用关键字aliased()

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-05
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2012-02-13
    • 2012-03-24
    • 1970-01-01
    相关资源
    最近更新 更多