开发者

Querying a view in SQLAlchemy

I want to know if SQLAlchemy has problems querying a view. If I query the view with normal SQL on the server like:

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

I get a whole bunch of records. But with SQLAlchemy I get only the first one. But in the count is the correct number. I have no ide开发者_如何学JAVAa why.

This is my SQLAlchemy code.

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()


if you've mapped ViewMyTable, the query will only return rows that have a fully non-NULL primary key. This behavior is specific to versions 0.5 and lower - on 0.6, if any of the columns have a non-NULL in the primary key, the row is turned into an instance. Specify the flag allow_null_pks=True to your mappers to ensure that partial primary keys still count :

mapper(ViewMyTable, myview, allow_null_pks=True)

If OTOH the rows returned have all nulls for the primary key, then SQLAlchemy cannot create an entity since it can't place it into the identity map. You can instead get at the individual columns by querying for them specifically:

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


I was facing similar problem - how to filter view with SQLAlchemy. For table:

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

I'm filtering:

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

Hopefully it will help:)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜