Rag*_*fin 3 python dictionary peewee
我找到了关于如何使用字典创建新表条目的便捷答案。
现在,我想使用相同的方法更新条目。但是我不知道如何处理我要更新的特定表项。
我当前的版本如下所示:
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
Run Code Online (Sandbox Code Playgroud)
如您所见,我明确地处理了每个字段。我想将变量(名称,颜色)放入字典中,并使用此答案中提到的double-star-shortcut更新位于“ entry_index”位置的条目。但是我在文档中找不到合适的方法。
有谁知道如何做到这一点?
谢谢你的帮助!
莫夫
要更新对象,您可以:
entry = entries_index[idx]
entry.something = 'new value'
entry.another_thing = 'another thing'
entry.save()
Run Code Online (Sandbox Code Playgroud)
或者:
Entry.update(**{'something': 'new value', 'another_thing': 'another'}).where(Entry.id == entry.id).execute()
Run Code Online (Sandbox Code Playgroud)
所有这些都包含在文档中,请仔细阅读。按照快速入门一步一步来,我想你会对如何使用peewee有更清晰的了解。
双星快捷方式是python的东西。它允许您将字典扩展为方法中的关键字参数。这意味着您可以执行以下操作:
fruit = { "name": "Banana", "color": "yellow"}
some_method(**fruit)
Run Code Online (Sandbox Code Playgroud)
这等同于做:
some_method(name="Banana", color="yellow")
Run Code Online (Sandbox Code Playgroud)
我认为这对您没有帮助。您已经更新了所选条目上的值,接下来要做的就是保存它们。
根据peewee docs的介绍,创建实例后,任何保存调用都会导致该实例被更新。这意味着您只需要调用该save
方法来更新更改的值。如果添加final entries[entry_index].save()
,则这些更改应保持不变。