Peewee - Update Existing Records



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

Example - Updating User age

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

main.py

from peewee import *

db = SqliteDatabase('mydatabase.db')

class User (Model):
   name=TextField()
   age=IntegerField()
   class Meta:
      database=db
      db_table='User'
	  
row=User.get(User.name=="Amar")
print ("name: {} age: {}".format(row.name, row.age))
row.age=25
row.save()
print("Record Updated.")

Output

name: Amar age: 20
Record Updated.

Example - Update records using update() method

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

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

main.py

from peewee import *

db = SqliteDatabase('mydatabase.db')

class User (Model):
   name=TextField()
   age=IntegerField()
   class Meta:
      database=db
      db_table='User'
	  
qry=User.update({User.age:25}).where(User.age>20)
print (qry.sql())
qry.execute()

print("Record Updated.")

Output

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

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

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.

Example - Update age by row indexes

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

main.py

from peewee import *

db = SqliteDatabase('mydatabase.db')

class User (Model):
   name=TextField()
   age=IntegerField()
   class Meta:
      database=db
      db_table='User'

rows=User.select()
rows[0].age=25
rows[2].age=23
User.bulk_update([rows[0], rows[2]], fields=[User.age])
print("Records Updated.")

Output

Records Updated.
Advertisements