Peewee 简明教程
Peewee - Update Existing Records
可以调用模型实例或 update() 类方法上的 save() 方法来修改现有数据。
Existing data can be modified by calling save() method on model instance as well as with update() class method.
以下示例在 get() 方法的帮助下从 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.
row=User.get(User.name=="Amar")
print ("name: {} age: {}".format(row.name, row.age))
row.age=25
row.save()
方法类的 update() 方法生成 UPDATE 查询。然后调用查询对象的 execute() 方法。
The update() method of Method class generates UPDATE query. The query object’s execute() method is then invoked.
以下示例使用 update() 方法来更改其中 age 列 >20 的行的 age 列。
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()
update() 方法呈现的 SQL 查询如下 −
The SQL query rendered by update() method is as follows −
('UPDATE "User" SET "age" = ? WHERE ("User"."age" > ?)', [25, 20])
Peewee 还有 bulk_update() 方法,以帮助在单个查询操作中更新多个模型实例。该方法需要更新的模型对象以及要更新的字段列表。
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.
以下示例通过新值更新指定行的 age 字段。
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])