I have a list of users in a table. User X browsing the table should be able to sort the list of users based on geographical proximity to User X. I have the distances between users stored in a separate table. My question is: how can I add a column of geographical distances into the data grid, to display alongside the columns of user names (ex. “Mike, 3 km from you”)? I can’t add a column from the IDE and then populate this column with geographical distances because users (who may use the app simultaneously) need to see a unique list of geographical distances based on their own location.
Have you tried populating the Data Grid from a list of dictionaries? You can construct the data for the current user using anvil.users.get_user()
.
Assuming you have a function to get the distance between two users, you could add a key for the distance to the other keys in your users table. Something like this:
me = anvil.users.get_user()
data_grid_data = []
for other_user in app_tables.users.search():
row = dict(me)
row.update({'distance_from_me': get_mutual_distance(me, other_user)})
data_grid_data.append(row)
Thanks Shaun! Your solution worked.
Due to an implementation problem in Anvil, the dict() function has to be modified to
row = dict(list(other_user))
Stephen, the implementation problem you mention is only on the client side and the workaround you mention works just fine. But in order for your code to work you need to give the form access to the table.
It is usually better to create a server module and collect the data on the server side, then pass a list of dictionaries to the form. It is better because:
- More power: you have full Python, not a 2.7 limited version
- Faster: you access all the tables you want while you build your list of dictionaries and return it to the form in one shot. Just one round trip. (See here)
- Safer: no need to give table access to the form.
Stefano,
Thanks for the excellent advice, really appreciate it.