1

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)
1

2 Answers 2

1

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

1 Comment

Thanks man! Never heard of getattr() before. This is very helpfull.
0

Will

print(dict(row)[key])

do the job for you?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.