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
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.
The double star shortcut is a python thing. It allows you to expand a dictionary into key-word arguments in a method. That means you can do something like this:
fruit = { "name": "Banana", "color": "yellow"}
some_method(**fruit)
which would be the equivelent of doing:
some_method(name="Banana", color="yellow")
I don't think that's helpful to you here though. You've already updated the values on the selected entry and all you need to do next is save them.
According to the peewee docs, once you have created an instance, any calls to save will cause that instance to be updated. That means you only need to call the save method to update the values you've changed. If you add a final entries[entry_index].save(), that should persist those changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With