Return last N rows from table

Getting the last 5 rows returned by a search requires Python to scan the whole table, read every row and discard them only to keep the last 5.

The correct way is to reverse the order and get the first 5 rows during the search. Then, since it’s just 5 rows, you can sort them once they are in memory.

In this little (untested) snippet I’m getting an iterator with 5 elements, converting it to list so it can be reversed and assigned to items:

last_5_rows = app_tables.mytable.search(tables.order_by('date', ascending=False))[:5]
last_5_rows = list(last_5_rows)
self.repeating_panel.items = reversed(last_5_rows)
2 Likes