Peewee - Insert New Record
In Peewee, there are more than one commands by which, it is possible to add a new record in the table. We have already used save() method of Model instance.
rec1=User(name="Rajesh", age=21) rec1.save()
The Peewee.Model class also has a create() method that creates a new instance and add its data in the table.
User.create(name="Kiran", age=19)
In addition to this, Model also has insert() as class method that constructs SQL insert query object. The execute() method of Query object performs adding a row in underlying table.
q = User.insert(name='Lata', age=20) q.execute()
The query object is an equivalent INSERT query.q.sql() returns the query string.
print (q.sql())
('INSERT INTO "User" ("name", "age") VALUES (?, ?)', ['Lata', 20])
Example - Inserting Records
Here is the complete code that demonstrates the use of above ways of inserting record.
main.py
from peewee import *
db = SqliteDatabase('mydatabase.db')
class User (Model):
name=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
db.create_tables([User])
rec1=User(name="Rajesh", age=21)
rec1.save()
a=User(name="Amar", age=20)
a.save()
User.create(name="Kiran", age=19)
q = User.insert(name='Lata', age=20)
q.execute()
db.close()
Output
We can verify the result in SQLiteStudio GUI.
Bulk Inserts
In order to use multiple rows at once in the table, Peewee provides two methods: bulk_create and insert_many.
insert_many()
The insert_many() method generates equivalent INSERT query, using list of dictionary objects, each having field value pairs of one object.
rows=[{"name":"Rajesh", "age":21}, {"name":"Amar", "age":20}]
q=User.insert_many(rows)
q.execute()
Here too, q.sql() returns the INSERT query string is obtained as below −
print (q.sql())
('INSERT INTO "User" ("name", "age") VALUES (?, ?), (?, ?)', ['Rajesh', 21, 'Amar', 20])
bulk_create()
This method takes a list argument that contains one or more unsaved instances of the model mapped to a table.
a=User(name="Kiran", age=19) b=User(name='Lata', age=20) User.bulk_create([a,b])
Example - Bulk Insert Operations
Following code uses both approaches to perform bulk insert operation.
main.py
from peewee import *
db = SqliteDatabase('mydatabase.db')
class User (Model):
name=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
db.create_tables([User])
rows=[{"name":"Rajesh", "age":21}, {"name":"Amar", "age":20}]
q=User.insert_many(rows)
q.execute()
a=User(name="Kiran", age=19)
b=User(name='Lata', age=20)
User.bulk_create([a,b])
db.close()