Peewee - Update Existing Records



Existing data can be modified by calling save() method on model instance as well as with update() class method.

Following example fetches a row from User table with the help of get() method and updates it by changing the value of age field.

row=User.get(User.name=="Amar")
print ("name: {} age: {}".format(row.name, row.age))
row.age=25
row.save()

The update() method of Method class generates UPDATE query. The query object’s execute() method is then invoked.

Following example uses update() method to change the age column of rows in which it is >20.

qry=User.update({User.age:25}).where(User.age>20)
print (qry.sql())
qry.execute()

The SQL query rendered by update() method is as follows −

('UPDATE "User" SET "age" = ? WHERE ("User"."age" > ?)', [25, 20])

Peewee also has a bulk_update() method to help update multiple model instance in a single query operation. The method requires model objects to be updated and list of fields to be updated.

Following example updates the age field of specified rows by new value.

rows=User.select()
rows[0].age=25
rows[2].age=23
User.bulk_update([rows[0], rows[2]], fields=[User.age])
Advertisements