DEV Community

Free Python Code
Free Python Code

Posted on

How to add update, and delete data in peewee Database Python

Hi 🙂🖐

In this post, I will share with you How to add update, and delete data in peewee Database Python.

What is peewee

Peewee is a simple and small ORM. It has few (but expressive) concepts, making it easy to learn and intuitive to use.

Install peewee

pip install peewee
Enter fullscreen mode Exit fullscreen mode

Create User Model

from peewee import SqliteDatabase, Model, CharField, IntegerField, UUIDField
from uuid import uuid4

# create database
db = SqliteDatabase('database.db')

# create user model
class User(Model):
    name = CharField(max_length=10)
    age = IntegerField()
    userId = UUIDField(primary_key=True)

    class Meta:
        database = db

# connect to db
db.connect()

# create users table 
db.create_tables([User])

db.commit()
Enter fullscreen mode Exit fullscreen mode

Add new data into table

user = User.create(name = 'test4', age = 10, userId = uuid4())
user.save()
Enter fullscreen mode Exit fullscreen mode

Update user name

# Update user data
User.update(name = '123456').where(
    User.userId == '639bbd66-b0e2-4259-b751-1ee2c7edf1d1'
).execute()


for user in User.select():
    print(user.name, user.userId)
Enter fullscreen mode Exit fullscreen mode

Delete user data

User.delete_by_id(pk = '639bbd66-b0e2-4259-b751-1ee2c7edf1d1')
Enter fullscreen mode Exit fullscreen mode

Note
pk == primary_key

Delete user by name

User.delete().where(User.name == 'test2').execute()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)