Search code examples
pythondictionarypeewee

Peewee - Update an entry with a dictionary


I found this handy answer on how to create a new table entry using a dictionary.

Now i'd like to update an entry with the same method. but i don't know how to adress the specific table entry that i'd like to update.

My current version looks like this:

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

As you can see i adress every field explicitly. I would like to put the variables (name, color) in a dictionary and update the entry at position "entry_index" with the fore-mentioned double-star-shortcut like in this answer. But i can't find a proper method in the docs.

Does anyone know how to accomplish that?

Thanks for your help!

Muff


Solution

  • To update an object, you can:

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

    Alternatively:

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

    All of this is covered in the docs, please give them a thorough read. Follow the quick-start step by step and I think you will have a clearer idea of how to use peewee.