【问题标题】:tinydb: how to update a document with a conditiontinydb:如何使用条件更新文档
【发布时间】:2018-06-02 02:58:33
【问题描述】:

您好,我想更新一些与查询匹配的文档。因此,对于每个文档,我想更新字段 '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
 },...

tinydbdocumentation 中,我看到可以使用 set。否则,如果我不使用 Set,它会更新 all 我不想更新的文档db.update(dict)

【问题讨论】:

  • set('parent_id', current_element_id) 在 Python 中是非法的。您是否在程序的某处重新定义了内置的 set 函数?
  • 感谢@DyZ 的评论。我不确定他们为什么要在 TinyDB 中实现 set

标签: python python-3.x tinydb


【解决方案1】:

在文档中使用 write_backreplace 部分会更好

>>> 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)

【讨论】:

  • write_back 已在 4.0 中被删除(无缘无故)。
猜你喜欢
  • 1970-01-01
  • 2018-06-02
  • 2020-03-18
  • 2011-07-29
  • 2017-06-09
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多