Peewee – Insert a New Record


Peewee – Insert a 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])

Here is the complete code that demonstrates the use of above ways of inserting record.


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()

We can verify the result in SQLiteStudio GUI.


SQLite Stuidio 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])

Following code uses both approaches to perform bulk insert operation.


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()

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *