App_tables over Uplink

Does anyone have sample code for downloading (and uploading) all records from an app_table into a list of dictionaries or Pandas dataframe? I’ve been unsuccessful thus far in figuring out how to use the “LiveObjects” that are returned and can’t find any documentation on them. This is what I have so far:

import anvil.tables as tables
import anvil.tables.query as q
from anvil.tables import app_tables
custs = app_tables.customers.search(Name="*")

for c in custs:
    print(c)  #This doesn't appear to do anything

The Django ORM and shell_plus may have me spoiled but I’m hoping that I can do something similar with Anvil.

Thank you in advance!!

Jeff

Welcome, Jeff.

In your code, c is a dict-like object representing one row of the table. To get the value of column x out of c, you would subscript it, e.g., c['x']

When x’s column-type is “LiveObject” (a.k.a. Link) (see https://anvil.works/doc/#data_tables_types), it is stored in the database as a row_id: a string of characters that uniquely identifies a row from another table.

For details of row_ids, and the various ways you can use them in your Python code, see “Links Between Tables” under https://anvil.works/doc/#data_tables_api . Also suggest searching the Knowledge Base for row_id. There are plenty of Tutorials and Examples that will apply.

Glad to have you aboard!

I think that your search will only find customers with name exactly equal to '*'.

If you want to find customers with any name, then don’t put any filter, just .search().

Then you can print(dict(c)).

Also, assuming you are trying to retrieve all results you can leave the Name=“*” out, so instead of

you can just do this :

custs = app_tables.customers.search()

EDIT - @stefano.menci beat me to it :slight_smile:

@jeff Sure,

Uploading to DataTable from Pandas:

This assumes you have a dictionary with keys that match the column names in your DataTable (or “automatic column creating” is turned on in your Anvil IDE).

import pandas as pd

df=pd.DataFrame(my_dict)
list_of_dicts=df.to_dict('records') # converting to list of dicts

for d in list_of_dicts:
    app_tables.my_table.add_row(**d) # or you can specify kwargs explicitly (e.g., my_col=d['key'])

Downloading DataTable into Pandas:

This converts Anvil row objects to Python dictionaries. This example does not handle linked rows but you can extend this idea if needed.

list_of_dicts=[dict(r) for r in app_tables.my_table.search()]
df = pd.DataFrame(list_of_dicts)
1 Like

Thanks for the quick response everyone! That was exactly what I needed. :slight_smile:

Next step will be uploading new rows. I’ll do some more reading through the docs.

Jeff

1 Like