您好我想更新一些与查询匹配的文档。因此,对于每个文档,我想更新字段'parent_id'
当且仅当此文档具有ID greater then
,即6
for result in results:
db.update(set('parent_id', current_element_id),
result.get('id') > current_element_id )
错误:
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
应该更新的文档示例:
...,
{'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
},...
在 tinydb 的documentation中,我看到我可以使用设置。否则,如果我不使用设置,则会更新所有我不想要的文档db.update(dict)
。
答案 0 :(得分:3)
使用文档的write_back
到replace部分文档更好
>>> 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}]
根据我的情况实施
for result in results:
if result['parent_id'] != None:
result['parent_id'] = current_element_id
db.write_back(results)