Papouche Guinslyzinho
Papouche Guinslyzinho

Reputation: 5448

tinydb: how to update a document with a condition

Hi I would like to update some documents that match a query. So for each document I would like to update the field 'parent_id' if and only if this document have an ID greater then i.e. 6

        for result in results:
            db.update(set('parent_id', current_element_id), 
                      result.get('id') > current_element_id )

error:

Traceback (most recent call last):
  File "debug.py", line 569, in <module>
    convertxml=parse(xmlfile, force_list=('interface',))
  File "debug.py", line 537, in parse
    parser.Parse(xml_input, True)
  File "..\Modules\pyexpat.c", line 468, in EndElement
  File "debug.py", line 411, in endElement
    db.update(set('parent_id', current_element_id), result.get('id') > current_element_id )
  File "C:\ProgramData\Miniconda3\lib\site-packages\tinydb\database.py", line 477, in update
    cond, doc_ids
  File "C:\ProgramData\Miniconda3\lib\site-packages\tinydb\database.py", line 319, in process_elements
    if cond(data[doc_id]):
TypeError: 'bool' object is not callable

example of document that should be update:

...,
{'URI': 'http://www.john-doe/',
 'abbr': 'IDD',
 'affiliation': 'USA',
 'closed': False,
 'created': '2018-06-01 22:49:02.927347',
 'element': 'distrbtr',
 'id': 7,
 'parent_id': None
 },...

In the documentation of tinydb I see that I can use set. Otherwise if I don't use Set it will update all the document db.update(dict) which I don't want to.

Upvotes: 1

Views: 4084

Answers (1)

Papouche Guinslyzinho
Papouche Guinslyzinho

Reputation: 5448

Using the Docs using write_back to replace part of a document is better

>>> docs = db.search(User.name == 'John')
[{name: 'John', age: 12}, {name: 'John', age: 44}]
>>> for doc in docs:
...     doc['name'] = 'Jane'
>>> db.write_back(docs)  # Will update the documents we retrieved
>>> docs = db.search(User.name == 'John')
[]
>>> docs = db.search(User.name == 'Jane')
[{name: 'Jane', age: 12}, {name: 'Jane', age: 44}]

implementing it to my situation

for result in results:
    if result['parent_id'] != None:
        result['parent_id']  = current_element_id
db.write_back(results)

Upvotes: 4

Related Questions