Is it possible to get the table name from a table object?
Right now I’m doing this:
def get_table_name(table_obj):
for attr in dir(app_tables):
if getattr(app_tables, attr, None) == table_obj:
return attr
Gross…
It looks like table has no __name__ attribute or other obvious candidates.
Can you tell me what exactly are you trying to achieve with this? Some example would be helpful.
Also, while there is no documented way to get the table name from table obj, it is possible to get the table obj from name if that helps.
Using
app_tables["table_name"]
Thanks - I need to do the opposite.
We want to be able to use a clone of our database as well as the original. This will preserve our row id but change our table ids. We use these Anvil IDs in a range of ways that require us to make sure they never change. One option we are considering is to persist the current ID in a lookup table so that is injected into a get_id-like function and we can guarantee the Row ID is the same to the external consumers of it (even if the underlying table ID did change).
So instead of:
my_id = my_row.get_id()
We’d have:
my_id = get_row_id(my_row)
Right now to get to the Table ID, we need to:
- Get the Table ID by parsing the row id returned by
get_id
- Get the table object from that ID
- Get the table name from the table object
- Get the mapped ID
- Return a row id.
Here’s a clone link (start a server repl to run the tests):
I’m all ears on a better way…
What about making row ids a separate column too?
So you can run a function once that does something like this
for row in ...:
row['id'] = row.get_id()
Now instead of row.get_id(), you can do row[‘id’].
Anvil suggested this (objectively better) alternative:
from anvil.tables import app_tables
# Create a lookup by table object
TABLE_NAME_MAP = {}
for name in app_tables:
table = app_tables[name]
TABLE_NAME_MAP[table] = name
# when you need to get the name:
table_name = TABLE_NAME_MAP[table_obj]
2 Likes