How do I find the last record inserted?

I have searched this forum and the docs and I can’t seem to find a way to get the last record inserted in a table.

1 Like

Hmm, here are a few ways (there may be better solutions):

table_length=len(app_tables.my_table.search()) # does not load any rows
last_row=app_tables.my_table.search()[table_length-1]
last_row=list(app_tables.my_table.search())[-1] # casted to a list

I’m not 100% sure, but a row’s get_id() method, may always be incrementing, and if so, you could find the row with the largest row id. Although, the suggestions above seem better to me.

As I said, there may be better ways, but the top two seem to do the trick nicely.

1 Like

Using [-1] requires the whole table to be scanned and it could be slow with large tables.

Ordering the query and getting the first item requires no scan and is faster, but you need one column with an incremental or a timestamp value, so you can do:

last_row = app_tables.my_table.search(tables.order_by('timestamp', ascending=False))[0]
7 Likes