【问题标题】:Peewee - Update an entry with a dictionaryPeewee - 用字典更新条目
【发布时间】:2016-09-03 18:38:22
【问题描述】:

我找到了this handy answer,了解如何使用字典创建新表条目。

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

我当前的版本是这样的:

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 dictionary peewee


    【解决方案1】:

    要更新对象,您可以:

    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 中,请仔细阅读。跟着quick-start一步步走,相信你会对peewee的使用有更清晰的认识。

    【讨论】:

    • 只是想知道,在字典包含模型中未找到的名称/值对的情况下,预期的行为会是什么?它会被忽略吗?
    【解决方案2】:

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

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

    这相当于做:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-29
      • 2017-05-02
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      相关资源
      最近更新 更多