dieggo111
dieggo111

Reputation: 83

Call table values dynamically with sqlalchemy

Let's say I have a table named "info_test" mapped like this:

class db_info_test(BASE):

__tablename__ = "info_test"

id              = Column(Integer, primary_key=True)
name            = Column(String)
project         = Column(String)
manufacturer    = Column(String)

If I want to get the names of all items from that table I would do something like this:

import db_info_test     
for row in self.session.query(db_info_test):
    print(row.name)

which would print:

name_of_item_A
name_of_item_B
...

Now I want to create a very generall function that prints the value of a key, where the key is given by an argument of that function. Something like this:

def get_value(self, table, key):
    for row in self.session.query(table):
        print(row.key)

Upvotes: 1

Views: 993

Answers (2)

Ilja Everilä
Ilja Everilä

Reputation: 53017

In Python getattr() is used for getting attributes based on variables. As an addition, you don't need to query the whole model object and all its attributes, if all you want is just one:

def get_value(self, table, key):
    # Note the comma after value. It unpacks the 1-tuples.
    for value, in self.session.query(getattr(table, key)):
        print(value)

Upvotes: 1

Olaf Górski
Olaf Górski

Reputation: 164

Will

print(dict(row)[key])

do the job for you?

Upvotes: 0

Related Questions