A row is like a dictionary, there’s no actual ordering of columns. If you want to process them in a specific order, then you’d need to use something else to control the order (such as the list_columns if that’s somehow the order you want to process them in).
Specifically, Python’s notion of a dictionary: an object of Python’s dict type.
Later versions of Python did specify an order to the columns – the order in which they were added – but Anvil’s database infrastructure is built on other technology, so it does not preserve order.
Building on the previous responses: if printing out fieldnames (with data) in the order produced by list_columns has value for you, then the following server function should serve.
@anvil.server.callable
def print_data_in_listcolumns_order(table_name):
columns = eval(f"app_tables.{table_name}.list_columns()")
column_names = [d['name'] for d in columns]
rows = eval(f"app_tables.{table_name}.search()")
for row in rows:
for col in column_names:
print([col, row[col]])
res = []
cols = [c['name'] for c in app_tables.contact.list_columns()]
rows = app_tables.contact.search()
for row in rows:
entry = {}
for col in cols:
entry[col] = row[col]
res.append(entry)
print(json.dumps(res))
Does method “list_columns” list the columns as I see them on the database/table page?
Will it always list them in the displayed order? I don’t know. Probably not.
If you need to know the order in which the IDE displays the columns, there is a reliable place to look: your local Git repository’s anvil.yaml file. An excerpt from one of mine:
That’s doing more work than needed. The following will have the same effect.
for row in rows:
res.append(dict(row))
And then when you pull items out on the client you can use your tuple of column names to control the order in which they get processed.
You’d only want your original code if you want to pass a subset of the columns back to the client, where you’re not processing all the columns, just some of them.