python - Accessing SQLAlchemy table column names with variables -
i have dictionary of sort
{'category_id': 'women_shoes', 'product_id': 486778462l}
here category_id table name in mysql database. trying specified product_id table women_shoes. able achieve through code
class_name = globals()[each_itemset["category_id"].capitalize()] table_values = session.query(class_name).filter(class_name.product_id == each_itemset["product_id"]) each in table_values: print each.brand_name name = "brand_name"
up til here things work fine , able brand_name of product. want instead of giving statement
print each.brand_name
i want
name = "brand_name" print each.name
because don't want specify exact table name myself. want table column names class_name.table.columns.keys(), , iterate on each column name , supply name 1 one.
i following error when 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 sqlalchemy documentation , don't seem find answer. should done in scenario? appreciated.
if trying generate dictionary of objects attributes: values, can use built in python object attribute dictionay __dict__
in case
for each in table_values: print each.__dict__
if there foreign keys or cast mechanisms youd follow / use, need implement custom to_dict()
method class, , use that
Comments
Post a Comment