[SOLVED] Setting db & field dynamically

Here is your one liner:

getattr(app_tables, db_name).search(**{db_field: value})

Here is a little explanation.

You use the built-in getattr() function when you know the name of the attribute at runtime. These two are equivalent:

db_name = 'customers'
table = getattr(app_tables, db_name)

table = app_tables.customers

In Python you can use * to expand a list of positional arguments and ** to expand a dictionary of named arguments. The search() method expects you to name the columns as named arguments, so you can create a dictionary with the named arguments and expand it in the call with **. These two are equivalent:

db_field = 'surname'
value = 'Smith'
dic = {db_field: value}
table.search(**dic)

table.search(surname='Smith')

ADMIN EDIT: Use getattr() instead of __getattr__(). Explanation below! --Meredydd

2 Likes