在SQLAlchemy中查询视图
我想知道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 个回答
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')
希望这能帮到你:)
9
如果你已经映射了 ViewMyTable
,那么查询结果只会返回那些主键完全不为NULL的行。这种情况只适用于0.5版本及以下的版本 - 在0.6版本中,如果主键的任何列有非NULL的值,那么这一行就会被转化为一个实例。你可以在映射器中设置 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