How to Setting Default UUID for User Model in Peewee

PHOTO EMBED

Sun May 05 2024 07:04:00 GMT+0000 (Coordinated Universal Time)

Saved by @freepythoncode ##python #coding #python #api #programming #database #peewee #orm

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

db = SqliteDatabase('mydb.db')

# Create user Model
class User(Model):
    userId = UUIDField(primary_key = True, default = uuid4)
    name = CharField(max_length = 10)
    age = IntegerField()

    class Meta:
        database = db

# Connect to db
db.connect()
db.create_tables([User])
db.commit()

# Add new user to database
user = User.create(name = 'user123', age = 20)
user.save()

# Get all users
for user in User.select():
    print(user.name, user.userId)
content_copyCOPY