[英]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 因此,对于每个文档,我想更新字段
'parent_id'
当且仅当此文档的ID greater then
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 . 在tinydb的文档中 ,我看到我可以使用set 。 Otherwise if I don't use Set it will update all the document
db.update(dict)
which I don't want to. 否则,如果我不使用Set ,它将更新我不想要的所有文件
db.update(dict)
。
Using the Docs using write_back
to replace part of a document is better 使用
write_back
替换部分文档更好
>>> 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.