Eric MacLeod
Eric MacLeod

Reputation: 461

How can I query a database with a value to get another value with sqlalchemy?

I'm trying to query a database with a unique id value and get the value of a column within the same row.

class Accounts(Base):
     __tablename__ = 'Accounts'

    id = Column(Integer, unique=True)
    site = Column(Integer, primary_key=True)
    accounts = Column(Integer)
    followers = Column(Integer)

How can I query the table with an id number and return the value of the site cell?

Upvotes: 4

Views: 12085

Answers (2)

jumbopap
jumbopap

Reputation: 4137

This is covered in the Query docs. A query returns one or more model instances representing rows, and column data is stored on these instances as attributes.

account = session.query(Accounts).filter_by(id = <some_id>).first()
print account.site

Upvotes: 4

Tim Martin
Tim Martin

Reputation: 2509

If you just want the value of that specific column--i.e. "SELECT column_name FROM ..." instead of "SELECT * FROM ..."--you can specify it in the query.

accounts, = session.query(Account.accounts).filter_by(id=account_id).first()

You can even specify multiple:

accounts, followers = session.query(Account.accounts, Account.followers).filter_by(id=account_id).first()

Upvotes: 5

Related Questions