Get the row number (index) of a particular row in a data table

I generally try to avoid this… However, it came up that I need the actual row number of a row in a data table from a get search.

So for example, given the products table:

name | price
product_1 | price_1
product_2 | price_2
product_3 | price_3
product_4 | price_4

I would like to know the row number (which will be the 3rd row in this case) in the products table of the following row:

app_tables.products.get(price = price_3)

So some function I can use that returns the value 2 (zero-indexed) for this particular row. Any ways to get this value?

You can try

all_rows = app_tables.dresses.search() 

to get all rows from the table. Then check each rows to see if the value match and return index (some kind of count)

The row can be accessed using app_tables.dresses.search()[index]

if it doesn’t work, convert the all_rows to list of dicts and check as above

The issue can be solved very easy with AUTO_INCREMENT column which is not available at the moment.

Thanks @Tony.Nguyen. My temporary fix was indeed something like this…

@anvil.server.callable
def get_index(price):    
  index = 0
  for row_product in app_tables.products.search():
    if row_product['price'] == price:
      return index
    index += 1
  return 0

Which gets me the first index with this condition satisfied. However, my feeling was that there might be something built in already with the get function of a row that is more elegant.

I have also been in the need of some kind of incrementer. I basically need to flip through and display my data table one row at a time. The only way I could figure out how to get the “next” row from the current row was by keeping track of the row index and grabbing rows with app_tables.products.search()[index]

PS the example shows me check for floats by equality. This is just an example and not what I am actually doing.

Hi @gweber.lauraandleigh, as far as I am concerned, without AUTO_INCREMENT column, there is no easy way to get the index at the moment.

You can convert the result to list of dicts and use something like this, which is a bit better:

1 Like