【问题标题】:Querying a view in SQLAlchemy在 SQLAlchemy 中查询视图
【发布时间】:2011-01-06 08:02:07
【问题描述】:

我想知道 SQLAlchemy 在查询视图时是否有问题。如果我在服务器上使用普通 SQL 查询视图,例如:

SELECT * FROM ViewMyTable WHERE index1 = '608_56_56';

我得到了一大堆记录。但是使用 SQLAlchemy 我只得到第一个。但在计数是正确的数字。我不知道为什么。

这是我的 SQLAlchemy 代码。

myQuery = Session.query(ViewMyTable)
erg = myQuery.filter(ViewMyTable.index1 == index1.strip())

# Contains the correct number of all entries I found with that query.
totalCount = erg.count()
# Contains only the first entry I found with my query.
ergListe = erg.all()

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案1】:

    如果您已映射 ViewMyTable,则查询将仅返回具有完全非 NULL 主键的行。此行为特定于 0.5 及更低版本 - 在 0.6 上,如果任何列在主键中具有非 NULL,则该行将转换为实例。为您的映射器指定标志 allow_null_pks=True 以确保部分主键仍然计数:

    mapper(ViewMyTable, myview, allow_null_pks=True)
    

    如果 OTOH 返回的行的主键全部为空,则 SQLAlchemy 无法创建实体,因为它无法将其放入身份映射中。您可以通过专门查询它们来获取各个列:

    for id, index in session.query(ViewMyTable.id, ViewMyTable.index):
        print id, index
    

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 1970-01-01
      • 2012-01-29
      • 2018-12-06
      • 1970-01-01
      • 2022-01-16
      • 2021-10-18
      • 2022-01-24
      • 2018-08-09
      相关资源
      最近更新 更多