Working with Table and Row objects?

I often want to inspect Table and Row objects. Four things I’m trying to do and their gross workarounds:

‘Get’ from a row object if the column exists:

if 'my_column' in dict(row_object):
    value = row_object['my_column']
else:
    value = None

Find out if an object is a row object:

hasattr(row_object, 'get_id') 
# type(row_object) gives anvil._server.LiveObjectProxy

There must be a better way!! Any ideas?

SOLVED:
Credit to stucork:
Figure out the Table a row is associated with:

tables = [app_tables.Table1, app_tables.Table2]
for table in tables:
    if table.has_row(row_object)
        break
else: # no break
    raise Exception('row does not exist in any known table')

Credit to campopiano:
Figure out the columns in a table:

columns = app_tables.MyTable.list_columns()
# This returns a dict of columns and field types

Some ideas that come to mind:

list_columns() I’ve never used it but I believe you pass the table object in as an argument. You could extrapolate that to also find the columns associated with a table (your 1st question).

If the row object is a dict, I think you can go:

value = my_dict_row.get('some_key', <someDefaultValue>)

Thanks campopianoa!

Great find on the list_columns method of app_table objecsts! That checks that one off the list…

Row objects are ‘dict-like’ but they don’t have a get method (I definitely think they should)! Conversion of row objects to dictionaries causes other problems.

Dan

You can pass a row to the dict function and then use get on the resulting object.

As an alternative to 1 - tables have a has_row method.

tables = [app_tables.Table1, app_tables.Table2]
for table in tables:
    if table.has_row(row_object)
        break
else: # no break
    raise Exception('row does not exist in any known table')

Noted on the request to add useful dict-like methods to row objects.

1 Like

Thanks Owen!

I am under the impression that this costs an additional server-call (if done client-side). Is anyone able to confirm/deny?

Great, thanks stucork! I will take this as a solution since it’s significantly less gross… but suggest that it would be helpful if we could get the table directly from the row object somehow!

You might want to upvote this feature request

Since you already know the name of the type of object, one ‘less gross’ standard way is isinstance():

isinstance( row_object, anvil._server.LiveObjectProxy )

…will yield a boolean value of True :cake:

2 Likes