PepperoniPizza
PepperoniPizza

Reputation: 9102

Sqlalchemy get integer from text query

I am fighting with some legacy code and the correct way to get an integer value from the database. I am trying to get it like this:

db = make_session() # this returns a session
q = db.query('count').from_statement(text("""
    SELECT count(1) as count FROM mytable
    WHERE somevar=:somevar;
""")).params(somevar=1)
return [p[0] for p in q]

This returns [81L]. I would also think that the value is q[0] but that raises and Exception. What is the correct way to use Sqlalchemy in this case and get only an integer here.

Upvotes: 0

Views: 2420

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155363

Presumably you'd want .scalar(). For example, something like this might be what you're looking for:

db.query(func.count(mytable.id).filter(mytable.somevar == 1)).scalar()

Upvotes: 3

Related Questions