Exporting csv with linked tables

Hello @sean and welcome to the forum.

This is a good question.

AFAIK the only way to represent your linked columns in a human-readable manner is to construct your own CSV, to your liking, from the related data tables.

For example, you can loop through the rows from your main table, store the information you want as a string (even from the linked rows), and use that string to create an Anvil Media object. The Media object can then be downloaded as a CSV.

Here is an example where I have two tables: Orders and Products. You can see that the code loops through each order and pulls out data from the linked Product table (product name, and product department). It then turns everything into a string (serializes) so that it can be made into a downloadable Media object.

# in a server module

@anvil.server.callable
def get_media():
  
  my_string=""
  for row in app_tables.orders.search():
    
    order_date=row['date'].strftime("%B %d, %Y").replace(',','') # some formatting
    order_name=row['product']['name'] # linked row
    product_dept=row['product']['department'] # linked row
    
    record=','.join([str(order_date),str(order_name),str(product_dept)])+'\n'
    my_string+=record
  
  media=anvil.BlobMedia('text/csv',my_string,name='my_new.csv')
  
  return media

On the client side, a button is set to trigger the download:

def button_1_click(self, **event_args):
  """This method is called when the button is clicked"""

  m=anvil.server.call('get_media')
  download(m)

Here’s a clone of the app so you can try it for yourself:

I shamelessly stole this approach from this thread (thanks @david.wylie) :

Your code will look different of course, especially if you want to extract all of your columns, but this is just an example to give you the gist.

There may be a better way, but it’s late and this is the best I could come up with. Good luck!

1 Like