在SQLAlchemy中查询视图

8

我想了解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()
2个回答

9

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

mapper(ViewMyTable, myview, allow_null_pks=True)

如果返回的行中主键都为null,则SQLAlchemy无法创建实体,因为它无法将其放入标识映射中。您可以通过特定查询单独获取每个列:

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

0

我曾经遇到过类似的问题 - 如何使用SQLAlchemy过滤视图。对于表格:

t_v_full_proposals = Table(
    'v_full_proposals', metadata,
    Column('proposal_id', Integer),
    Column('version', String),
    Column('content', String),
    Column('creator_id', String)
)

我正在进行过滤:

proposals = session.query(t_v_full_proposals).filter(t_v_full_proposals.c.creator_id != 'greatest_admin')

希望它会有所帮助 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接