0

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.

1
  • 1
    Possibly q.one().count Commented Dec 1, 2015 at 4:48

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.