I am trying to get the last record from my tinyDB, so I want to make a query that looks like that:
"SELECT * FROM table ORDER BY id DESC LIMIT 1"
which should give me the last row. though I can't figure out how to do it with TinyDB.
Asked
Active
Viewed 4,011 times
1

TheDragoner
- 273
- 2
- 6
- 17
4 Answers
2
If you want to order db by time descending for example:
od = sorted(db.all(), key=lambda k: k['time'])
print(od[-1])

Synal
- 75
- 3
- 11
1
According to the documentation, the following would return the doc id of the final element in the db in TinyDB 4.7.0:
el = db.all()[-1]
record = db.get(doc_id=el.doc_id)

teggy
- 11
- 2
0

enpith
- 1,540
- 2
- 10
- 11
-
2You should not compare doc_id value and len(table) if you made some remove removed. If you have `{"1":{...}, "2":{...}, "3":{...}}` if you do : `t.remove(doc_ids=[2])` you obtains: `{"1":{...}, "3":{...}}` – blobmaster Jul 03 '20 at 08:50
0
Using a Query
and doing an update :
with TinyDB('db.json') as db:
my_table = db.table('a_table_name')
my_query= Query()
first_of_table_for_this_query = my_table.search(my_query.some_field == some_value)[1]
last_of_table_for_this_query = my_table.search(my_query.some_field == some_value)[-1]
# exemple of use for updating first inserted and last inserted only
my_table.update({'some_field': some_value+42}, doc_ids=[
first_of_table_for_this_query,
last_of_table_for_this_query
])

blobmaster
- 853
- 8
- 11