Falconic
Falconic

Reputation: 317

Accessing SQLAlchemy table column names with variables

I have a dictionary of the sort

{'category_id': 'women_shoes', 'product_id': 486778462L}

Here category_id is my table name in MYSQL database. I am trying to get the specified product_id from the table women_shoes. I am able to achieve this through this code

class_name = globals()[each_itemset["category_id"].capitalize()]
table_values = session.query(class_name).filter(class_name.product_id == each_itemset["product_id"])
for each in table_values:               
    print each.brand_name               
    name = "brand_name"

Up til here things work fine and I am able to get the brand_name of the product. What I want is that instead of giving the statement

print each.brand_name

I want to do

name = "brand_name"
print each.name

because I don't want to specify the exact table name myself. I want to get the table column names from class_name.table.columns.keys(), and iterate over it to get each column name and supply it to name one by one.

I get the following error when I do this

Traceback (most recent call last):
  File "main_site.py", line 14, in <module>
    json_data = db_access.get_styles_from_db("work")
  File "C:\Python27\Projects\Clothe Studio Recommendation Project\util\db_access.py", line 149, in get_styles_from_db
    calc_outfit_scores(outfit_dict, session)
  File "C:\Python27\Projects\Clothe Studio Recommendation Project\util\db_access.py", line 192, in calc_outfit_scores
    print each.name
AttributeError: 'Women_shoes' object has no attribute 'name'

I have searched through the SQLAlchemy documentation and SO but don't seem to find an answer. What should be done in this scenario? Your help is appreciated.

Upvotes: 0

Views: 1483

Answers (2)

flazzarini
flazzarini

Reputation: 8181

You could use getattr to retrieve the attribute in a more generic way.

for each in table_values:      
    name = 'brand_name'
    value = getattr(each, name)
    print(value)

Upvotes: 0

Busturdust
Busturdust

Reputation: 2485

If you are simply trying to generate a dictionary of the objects attributes: values, you can use the built in python object attribute dictionay __dict__

in your case

for each in table_values:               
    print each.__dict__

If there are any Foreign Keys or cast like mechanisms youd like to follow / use, you will need implement a custom to_dict() method for the class, and use that

Upvotes: 1

Related Questions