Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 706
Eric MacLeod Avatar asked Oct 23 '25 09:10

Eric MacLeod


2 Answers

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()
like image 164
Tim Martin Avatar answered Oct 26 '25 00:10

Tim Martin


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
like image 43
jumbopap Avatar answered Oct 26 '25 02:10

jumbopap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!