A lightweight Python ORM (Object-Relational Mapping) library that provides a simple and expressive interface for database operations.
—
Core ORM functionality for defining database models, field types, relationships, and performing CRUD operations. This forms the foundation of Peewee's object-relational mapping capabilities.
Base model class that provides the Active Record pattern for database table mapping. Models define the structure and behavior of database tables through field definitions and metadata.
class Model:
"""
Base model class for all database models.
"""
def save(self, force_insert=False, only=None):
"""
Save the model instance to database.
Parameters:
- force_insert (bool): Force INSERT instead of UPDATE
- only (list): Only save specified fields
Returns:
int: Number of rows affected
"""
def delete_instance(self, recursive=False, delete_nullable=False):
"""
Delete this model instance from database.
Parameters:
- recursive (bool): Delete related objects
- delete_nullable (bool): Delete nullable related objects
Returns:
int: Number of rows deleted
"""
@classmethod
def create(cls, **kwargs):
"""
Create and save a new model instance.
Parameters:
- **kwargs: Field values for the new instance
Returns:
Model: The created instance
"""
@classmethod
def get(cls, *query, **filters):
"""
Get a single model instance matching the query.
Parameters:
- *query: Query expressions
- **filters: Field filters
Returns:
Model: The matching instance
Raises:
DoesNotExist: If no matching instance found
"""
@classmethod
def get_or_create(cls, **kwargs):
"""
Get existing instance or create new one.
Parameters:
- **kwargs: Field values to match or create with
Returns:
tuple: (instance, created) where created is bool
"""
@classmethod
def select(cls, *fields):
"""
Create a SELECT query for this model.
Parameters:
- *fields: Fields to select (defaults to all)
Returns:
Select: Query instance
"""
@classmethod
def update(cls, **fields):
"""
Create an UPDATE query for this model.
Parameters:
- **fields: Field values to update
Returns:
Update: Query instance
"""
@classmethod
def delete(cls):
"""
Create a DELETE query for this model.
Returns:
Delete: Query instance
"""
@classmethod
def create_table(cls, fail_silently=False):
"""
Create the database table for this model.
Parameters:
- fail_silently (bool): Don't raise error if table exists
"""
@classmethod
def drop_table(cls, fail_silently=False, cascade=False):
"""
Drop the database table for this model.
Parameters:
- fail_silently (bool): Don't raise error if table doesn't exist
- cascade (bool): Drop dependent objects
"""
@classmethod
def truncate_table(cls, restart_identity=False, cascade=False):
"""
Truncate the database table for this model.
Parameters:
- restart_identity (bool): Restart sequence counters
- cascade (bool): Truncate dependent tables
"""
class CompositeKey:
"""
Support for composite primary keys across multiple fields.
"""
def __init__(self, *field_names):
"""
Parameters:
- *field_names: Names of fields forming the composite key
"""Usage example:
from peewee import *
db = SqliteDatabase('example.db')
class User(Model):
username = CharField(unique=True)
email = CharField()
is_active = BooleanField(default=True)
class Meta:
database = db
table_name = 'users'
indexes = (
(('username', 'email'), True), # Unique index
)
# Create and save instance
user = User.create(username='john', email='john@example.com')
# Get instance
user = User.get(User.username == 'john')
# Update instance
user.email = 'newemail@example.com'
user.save()
# Delete instance
user.delete_instance()Base field class and all available field types for database column definitions. Fields provide type safety, validation, and database-specific conversion.
class Field:
"""
Base class for all field types.
"""
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):
"""
Parameters:
- null (bool): Allow NULL values
- index (bool): Create database index
- unique (bool): Enforce uniqueness constraint
- column_name (str): Custom column name
- default: Default value or callable
- primary_key (bool): Make field primary key
- constraints (list): Additional SQL constraints
- sequence (str): Database sequence name
- collation (str): String collation
- unindexed (bool): Disable indexing for this field
- choices (list): Valid choices for field
- help_text (str): Documentation text
- verbose_name (str): Human-readable name
- validators (list): Validation functions
"""
class AnyField(Field):
"""Field that accepts any data type without conversion."""
class BareField(Field):
"""Raw field with no type conversion logic."""
# Integer Fields
class IntegerField(Field):
"""Standard 32-bit integer field."""
class BigIntegerField(Field):
"""64-bit integer field for large numbers."""
class SmallIntegerField(Field):
"""16-bit integer field for small numbers."""
class AutoField(Field):
"""Auto-incrementing integer primary key."""
class BigAutoField(Field):
"""Auto-incrementing 64-bit integer primary key."""
class IdentityField(Field):
"""PostgreSQL identity column with auto-generation."""
class PrimaryKeyField(AutoField):
"""Deprecated auto-incrementing primary key (use AutoField)."""
# Numeric Fields
class FloatField(Field):
"""Single-precision floating-point field."""
class DoubleField(Field):
"""Double-precision floating-point field."""
class DecimalField(Field):
"""
Fixed-precision decimal field for financial data.
Parameters:
- max_digits (int): Maximum total digits
- decimal_places (int): Decimal places
- auto_round (bool): Automatically round values
- rounding (str): Rounding mode
"""
# String Fields
class CharField(Field):
"""
Variable-length character field.
Parameters:
- max_length (int): Maximum string length
"""
class FixedCharField(CharField):
"""Fixed-length character field, padded if necessary."""
class TextField(Field):
"""Large text field for unlimited text storage."""
# Binary Fields
class BlobField(Field):
"""Binary large object field for file data."""
class BitField(Field):
"""
Bit field for storing boolean flags efficiently.
Parameters:
- flags (dict): Named flags mapping
"""
class BigBitField(BitField):
"""Large bit field for many boolean flags."""
# Date/Time Fields
class DateField(Field):
"""
Date field (YYYY-MM-DD format).
Parameters:
- formats (list): Accepted date formats
"""
class TimeField(Field):
"""
Time field (HH:MM:SS format).
Parameters:
- formats (list): Accepted time formats
"""
class DateTimeField(Field):
"""
Combined date and time field.
Parameters:
- formats (list): Accepted datetime formats
"""
class TimestampField(BigIntegerField):
"""
Unix timestamp field with configurable resolution.
Parameters:
- resolution (int): Timestamp resolution (1=seconds, 1000=milliseconds, etc.)
- utc (bool): Use UTC time for default values
"""
# Special Fields
class BooleanField(Field):
"""Boolean true/false field."""
class UUIDField(Field):
"""UUID field for unique identifiers."""
class BinaryUUIDField(UUIDField):
"""Binary UUID field for space efficiency."""
class IPField(BigIntegerField):
"""IPv4 address field stored as 32-bit integer."""Usage examples:
class Product(Model):
name = CharField(max_length=100)
description = TextField()
price = DecimalField(max_digits=10, decimal_places=2)
created_at = DateTimeField(default=datetime.datetime.now)
is_active = BooleanField(default=True)
tags = BitField() # For feature flags
class Meta:
database = dbForeign key and many-to-many relationship fields for modeling database relationships between tables.
class ForeignKeyField(Field):
"""
Foreign key relationship to another model.
"""
def __init__(self, model, field=None, backref=None, on_delete=None,
on_update=None, deferrable=None, lazy_load=True, **kwargs):
"""
Parameters:
- model: Target model class or string name
- field: Target field (defaults to primary key)
- backref (str): Name for reverse relationship
- on_delete (str): Cascade behavior ('CASCADE', 'SET NULL', etc.)
- on_update (str): Update cascade behavior
- deferrable (str): Deferrable constraint mode
- lazy_load (bool): Enable lazy loading
- **kwargs: Additional Field parameters
"""
class ManyToManyField(Field):
"""
Many-to-many relationship through intermediate table.
"""
def __init__(self, model, backref=None, through_model=None, **kwargs):
"""
Parameters:
- model: Target model class
- backref (str): Name for reverse relationship
- through_model: Custom intermediate model
- **kwargs: Additional Field parameters
"""
class DeferredForeignKey(Field):
"""
Deferred foreign key for circular references.
"""
def __init__(self, rel_model_name, **kwargs):
"""
Parameters:
- rel_model_name (str): Name of target model
- **kwargs: ForeignKeyField parameters
"""Usage examples:
class User(Model):
username = CharField(unique=True)
email = CharField()
class Meta:
database = db
class Post(Model):
title = CharField()
content = TextField()
author = ForeignKeyField(User, backref='posts')
created_at = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
class Tag(Model):
name = CharField()
class Meta:
database = db
class PostTag(Model):
post = ForeignKeyField(Post)
tag = ForeignKeyField(Tag)
class Meta:
database = db
primary_key = CompositeKey('post', 'tag')
# Many-to-many through intermediate model
Post.tags = ManyToManyField(Tag, backref='posts', through_model=PostTag)
# Usage
user = User.create(username='john', email='john@example.com')
post = Post.create(title='Hello', content='World', author=user)
# Access relationships
print(f"Post author: {post.author.username}")
print(f"User posts: {list(user.posts)}")Configuration options for model behavior, database table settings, and constraints.
class Model:
class Meta:
"""
Model metadata configuration.
"""
database = None # Database instance
table_name = None # Custom table name
indexes = () # Index definitions
primary_key = None # Composite primary key
constraints = () # Table constraints
schema = None # Database schema
only_save_dirty = False # Only save changed fields
legacy_table_names = False # Use legacy naming
depends_on = () # Model dependencies
without_rowid = False # SQLite WITHOUT ROWID
strict_tables = False # SQLite STRICT tables
table_function = False # Table-valued function
temporary = False # Temporary tableclass Model:
def validate(self, field_dict=None, exclude=None):
"""
Validate model instance.
Parameters:
- field_dict (dict): Override field values
- exclude (list): Fields to exclude from validation
Raises:
ValidationError: If validation fails
"""
def is_dirty(self):
"""
Check if model has unsaved changes.
Returns:
bool: True if model has changes
"""
def dirty_fields(self):
"""
Get list of fields with unsaved changes.
Returns:
list: Modified field names
"""Custom field validation with validators:
from peewee import *
def validate_email(value):
if '@' not in value:
raise ValueError('Invalid email format')
class User(Model):
email = CharField(validators=[validate_email])
age = IntegerField(constraints=[Check('age >= 0')])
class Meta:
database = dbInstall with Tessl CLI
npx tessl i tessl/pypi-peewee