Peewee - 用字典更新条目

Peewee - Update an entry with a dictionary

我发现 this handy answer 如何使用字典创建 新的 table 条目。

现在我想用同样的方法更新一个条目。但我不知道如何处理我想更新的特定 table 条目。

我当前的版本是这样的:

entries = Fruit.select().order_by(Fruit.name.desc())
#... all entries are listed with the index number
entry_index = int(input("Please enter entry number: "))
#...
entry_index -= 1

name = "Banana"
color = "yellow"

if input('Update entry? [Yn] ').lower() != 'n':
        entries[entry_index].name = name
        entries[entry_index].color = color

如您所见,我明确指出了每个字段。 我想将变量(名称、颜色)放入字典中,并使用上述双星快捷键 like in this answer 更新位置 "entry_index" 处的条目。 但是我找不到 proper method in the docs

有谁知道如何做到这一点?

感谢您的帮助!

手筒

双星快捷方式是 python 东西。它允许您将字典扩展为方法中的关键字参数。这意味着您可以这样做:

fruit = { "name": "Banana", "color": "yellow"}
some_method(**fruit)

这相当于做:

some_method(name="Banana", color="yellow")

不过我认为这对您没有帮助。您已经更新了所选条目的值,接下来需要做的就是保存它们。

According to the peewee docs,一旦您创建了一个实例,任何对保存的调用都会导致该实例被更新。这意味着您只需要调用 save 方法来更新您更改的值。如果您添加一个最终的 entries[entry_index].save(),那应该会保留这些更改。

要更新对象,您可以:

entry = entries_index[idx]
entry.something = 'new value'
entry.another_thing = 'another thing'
entry.save()

或者:

Entry.update(**{'something': 'new value', 'another_thing': 'another'}).where(Entry.id == entry.id).execute()

所有这些都在 docs, please give them a thorough read. Follow the quick-start 中逐步介绍,我想您会对如何使用 peewee 有更清晰的认识。