A lightweight Python ORM (Object-Relational Mapping) library that provides a simple and expressive interface for database operations.
npx @tessl/cli install tessl/pypi-peewee@3.18.0A lightweight Python ORM (Object-Relational Mapping) library that provides a simple and expressive interface for database operations. Peewee supports multiple database backends including SQLite, MySQL, MariaDB, and PostgreSQL, making it suitable for a wide range of applications from small scripts to larger web applications.
pip install peeweeimport peeweeMost common usage pattern:
from peewee import *Specific imports:
from peewee import Model, CharField, IntegerField, SqliteDatabasefrom peewee import *
# Define database
db = SqliteDatabase('my_app.db')
# Define model
class User(Model):
username = CharField(unique=True)
email = CharField()
age = IntegerField()
class Meta:
database = db
# Create tables
db.create_tables([User])
# Create records
user = User.create(username='john', email='john@example.com', age=25)
# Query records
users = User.select().where(User.age > 18)
for user in users:
print(user.username, user.email)
# Update records
User.update(age=26).where(User.username == 'john').execute()
# Delete records
User.delete().where(User.age < 18).execute()Peewee follows a simple architecture centered around a few key components:
The library emphasizes simplicity and expressiveness with a Django-like model definition syntax while maintaining high performance and minimal dependencies. The playhouse package provides extensive database-specific extensions, utilities, and advanced features like connection pooling, database reflection, migrations, and specialized field types.
Core ORM functionality including model definition, field types, relationships, and model operations. Provides the foundation for mapping Python objects to database tables with type-safe field definitions and relationship management.
class Model:
def save(self, force_insert=False, only=None): ...
def delete_instance(self, recursive=False, delete_nullable=False): ...
@classmethod
def create(cls, **kwargs): ...
@classmethod
def get(cls, *query, **filters): ...
@classmethod
def get_or_create(cls, **kwargs): ...
@classmethod
def select(cls, *fields): ...
@classmethod
def update(cls, **fields): ...
@classmethod
def delete(cls): ...
class Field:
def __init__(self, null=False, index=False, unique=False, column_name=None,
default=None, primary_key=False, constraints=None,
sequence=None, collation=None, unindexed=False, choices=None,
help_text=None, verbose_name=None, validators=None): ...
class ForeignKeyField(Field):
def __init__(self, model, field=None, backref=None, on_delete=None,
on_update=None, deferrable=None, lazy_load=True, **kwargs): ...Database connection management, transaction handling, and backend-specific functionality. Supports SQLite, PostgreSQL, MySQL, and connection proxying for multi-database scenarios.
class Database:
def connect(self, reuse_if_open=False): ...
def close(self): ...
def execute_sql(self, sql, params=None, commit=None): ...
def begin(self): ...
def commit(self): ...
def rollback(self): ...
def atomic(self, *args, **kwargs): ...
def transaction(self, *args, **kwargs): ...
def create_tables(self, models, **options): ...
def drop_tables(self, models, **options): ...
class SqliteDatabase(Database): ...
class PostgresqlDatabase(Database): ...
class MySQLDatabase(Database): ...
class DatabaseProxy(Database): ...Query building, filtering, joins, aggregation, and bulk operations. Provides a fluent interface for constructing complex SQL queries with Python syntax.
class Select:
def where(self, *expressions): ...
def join(self, dest, join_type='INNER', on=None): ...
def group_by(self, *columns): ...
def having(self, *expressions): ...
def order_by(self, *columns): ...
def limit(self, limit, offset=0): ...
def distinct(self, distinct=True): ...
def aggregate(self, aggregation): ...
def count(self, clear_limit=False): ...
def exists(self): ...
def get(self): ...
def fn(*args, **kwargs): ... # Function call builder
class Case: ... # SQL CASE expressions
class SQL: ... # Raw SQL expressions
def prefetch(*args, **kwargs): ... # Prefetch related objectsAdvanced database extensions, additional field types, connection pooling, database-specific features, and framework integrations provided by the playhouse package.
# Database extensions
from playhouse.postgres_ext import PostgresqlExtDatabase, ArrayField, JSONField
from playhouse.sqlite_ext import SqliteExtDatabase, FTSModel, JSONField
from playhouse.mysql_ext import MySQLConnectorDatabase, JSONField
# Connection pooling
from playhouse.pool import PooledPostgresqlDatabase, PooledMySQLDatabase
# Utilities and integrations
from playhouse.shortcuts import model_to_dict, dict_to_model
from playhouse.migrate import migrate, PostgresqlMigrator
from playhouse.flask_utils import FlaskDB, get_object_or_404
from playhouse.dataset import DataSetclass PeeweeException(Exception): ...
class ImproperlyConfigured(PeeweeException): ...
class DoesNotExist(PeeweeException): ...
class DatabaseError(PeeweeException): ...
class DataError(DatabaseError): ...
class IntegrityError(DatabaseError): ...
class InterfaceError(DatabaseError): ...
class InternalError(DatabaseError): ...
class NotSupportedError(DatabaseError): ...
class OperationalError(DatabaseError): ...
class ProgrammingError(DatabaseError): ...Common exception handling patterns:
from peewee import DoesNotExist, IntegrityError
try:
user = User.get(User.username == 'nonexistent')
except DoesNotExist:
print("User not found")
try:
User.create(username='duplicate', email='test@example.com')
except IntegrityError:
print("Username already exists")__version__ = '3.18.2'