I am creating an api for some simple forum using pyramid and sqlalchemy. I have a view which I want to simply return some posts in json form to the client, when the user scrolls down to the end of the page. For some reason, the query isn't even being run and I'm being returned a query object instead of a rowproxy object. This is just a test query btw, I'm just getting a few times from the db and trying to send them in json.
@view_config(route_name='get-posts', renderer='json')
def get-posts(request)
q = session.query(Topic).filter(Topic.name =='gaming')\
.order_by(desc(Topic.topic_date)).limit(10)
results = [dict(zip(row.keys()) for row in q)]
return {'posts' : results}
When this is run, I get "AttributeError: 'Topic' object has no attribtue keys", and upon checking the type of q, I discover it is of type:sqlalchemy.orm.query.Query
Does anyone know why the query is not being run? I have a non api view function where i'm doing practically the same thing, and returning the result ( a row proxy as the contents of a dictionary and it works...
This is by design. There are methods on query that cause execution of the underlying query. all(), one(), first(), etc.
If you need the query object as list, call all() on it:
@view_config(route_name='get-posts', renderer='json')
def get-posts(request)
q = session.query(Topic).filter(Topic.name =='gaming')\
.order_by(desc(Topic.topic_date)).limit(10)
return {'posts' : q.all()}
Reference for the query object: http://docs.sqlalchemy.org/en/latest/orm/query.html#the-query-object