Peewee is a Python library based on ORM (Object-Relational Mapping). Is is supports SQLite, MySQL, PostgreSQL, and Cockroach databases. In the following this tutorial, we will be learning how to insert a new record, delete a record, create an index, and a many more using the Peewee library function in the Python programming language. It develops by a US-based software engineer Charles Leifer in October 2010.

PeeWee Library Functions in Python

The Field Types in Peewee

This model define the storage type of the model.

Field TypeSQLitePostgreSQLMySQL
CharFieldVarcharVarcharVarchar
TextFieldTextTextLongtext
DateTimeFieldDatetimeTimestampDatetime
IntegerFieldIntegerIntegerInteger
BooleanFieldSmallintBooleanBool
FloatFieldRealRealReal
DoubleFieldRealDouble PrecisionDouble Precision
BigIntegerFieldIntegerBigintBigint
DecimalFieldDecimalNumericNumeric
PrimaryKeyFieldIntegerSerialInteger
ForeignKeyFieldIntegerIntegerInteger
DateFieldDateDateDate
TimeFieldTimeTimeTime
List of Functions

Example

# importing the required libraries  

import peewee  

import datetime  

# creating a database  

db = peewee.SqliteDatabase(‘testSpace.db’)  

# defining a class as Notes  

class Notes(peewee.Model):  

    text = peewee.CharField()  

    created = peewee.DateField(default = datetime.date.today)  

    class Meta:  

        database = db  

        db_table = ‘notes’  

  

# creating table  

Notes.create_table()  

noteOne = Notes.create(text = ‘Book Store’)  

noteOne.save()  

noteTwo = Notes.create(text = ‘Copy Store’, created = datetime.date(2022, 12, 6))  

noteTwo.save()  

noteThree = Notes.create(text = ‘Card Store’, created = datetime.date(2022, 12, 6))  

noteThree.save()  

noteFour = Notes.create(text = ‘pen Store’)  

noteFour.save()  

Output

sqlite> select * from notes;
1|Book Store|2022-12-07
2|Copy Store|2022-12-06
3|Card Store|2022-12-06
4|Pen Store|2022-12-07

Meta Class Attributes

  • Database
  • db_table
  • Indexes
  • primary_key
  • Constraints
  • Schema
  • Temporary
  • depends_on
  • without_rowid

Methods in Model class

  • Classmethod alias()
  • Classmethod select()
  • Classmethod update()
  • classmethod insert()
  • classmethod delete()
  • classmethod get()
  • get_id()
  • save()
  • classmethod bind()

Field Class

  • column_name (str)
  • primary_key (bool)
  • constraints (list)
  • choices (list)
  • null (bool)
  • index (bool)
  • unique (bool)
  • Default
  • collation (str)
  • help_text (str)
  • verbose_name (str)

Numeric Field classes

  • IntegerField
  • BigIntegerField
  • SmallIntegerField
  • FloatField
  • DoubleField
  • DecimalField

Text fields

  • CharField
  • FixedCharField
  • TextField

Binary fields

  • BlobField
  • BitField
  • BigBitField
  • UUIDField

Date and Time fields

  • DateTimeField
  • DateField
  • TimeField

ForeignKeyField

  • model (Model)
  • field (Field)
  • backref (str)
  • on_delete (str)
  • on_update (str)
  • lazy_load (bool)

Other Field Types

  • IPField
  • BooleanField
  • AutoField
  • IdentityField

Insert a New Record

Example of Insert a new 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="Tanisha", age=15)
rec1.save()
a=User(name="Amit", age=18)
a.save()
User.create(name="Swati", age=22)
q = User.insert(name='Abhinav', age=25)
q.execute()
db.close()

Bulk Inserts

Bulk Insert Peewee provides two methods : 

  • bulk_create 
  • insert_many

insert_many()

rows=[{"name":"Rohit", "age":18}, {"name":"Ritika", "age":22}]
q=User.insert_many(rows)
q.execute()

bulk_create()

a=User(name="Kiran", age=19)
b=User(name='Lata', age=20)
User.bulk_create([a,b])

Following code uses both insert_many() and bulk_create()

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":"Rohit", "age":18}, {"name":"Ritika", "age":23}]
q=User.insert_many(rows)
q.execute()
a=User(name="mohit", age=15)
b=User(name='mohine', age=16)
User.bulk_create([a,b])
db.close()

Select Records

Following code uses select Record

rom peewee import *
db = SqliteDatabase('mydatabase.db')
class User (Model):
   name=TextField()
   age=IntegerField()
   class Meta:
      database=db
      db_table='User'
rows=User.select()
print (rows.sql())
for row in rows:
   print ("name: {} age: {}".format(row.name, row.age))
db.close()

Filters

logical operatorsDescribe
==a equals b
<a is less than b
>a is greater than b
<=a is less than or equal to b
>=a is greater than or equal to b
!=a is not equal to b
<<a IN b, where b is a list or query
>>a IS b, where y is None and NULL
%a LIKE b where b may contain wildcards
**a ILIKE b where b may contain wildcards
^a XOR b
~Unary negation

Following code displays name with rupees>=600:

rows=User.select().where (User.rupees>=600)
for row in rows:
   print ("name: {} rupees: {}".format(row.name, row.rupees))

If you have any queries regarding this article or if I have missed something on this topic, please feel free to add in the comment down below for the audience. See you guys in another article.

To know more about PeeWee Library Function please Wikipedia Click here

Stay Connected Stay Safe, Thank you


Basic Engineer

Hey Readers! We have more than fifteen years of experience in Software Development, IoT, Telecom, Banking, Finance and Embedded domain. Currently we are actively working on Data Science, ML and AI with multiple market leaders worldwide. Happy Reading. Cheers!

0 Comments

Leave a Reply

Avatar placeholder

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