I am trying to query for a field in JSON column (Postgres):

class MyTable(Base):
    __tablename__ = 'my_table'

    data = Column(JSONB)

Query:

my_query = session.query(MyTable).limit(10).with_entities(MyTable.data['rule']).all()

I get no error, but the result is empty.

Even if I try with astext, same empty result:

my_query = session.query(MyTable).limit(10).with_entities(MyTable.data['rule'].astext).all()

Can I use with_entities in this case? What would be the work around? Thanks.

share|improve this question
    
Shouldn't the ['rule'] part be on the result, not in the with_entities field? – Paul Becotte Jul 27 at 18:34
    
@Paul Becotte: I do not think so. Otherwise, the whole purpose of accessing JSON fields from the query is lost. – jazzblue Jul 27 at 18:42
    
It works for me. (session.add(MyTable(data={"rule": "foo"})); session.flush(); session.query(MyTable)...) Perhaps you don't have any rows in your table? – univerio Jul 27 at 19:48
    
@univerio: I do, in fact when I query for another non-JSON column I get results. Could you post what your my_query[0] look like? – jazzblue Jul 27 at 19:52
    
(u'foo',). When you say the result is empty, my_query is the empty list? – univerio Jul 27 at 20:04

The addition of label() method solved the issue for me:

my_query = session.query(MyTable).limit(10). \
        with_entities(MyTable.data['rule'].label('rule')).all()
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.