简体   繁体   中英

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 ie 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM