or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

database-and-connections.mdextensions-playhouse.mdindex.mdmodels-and-fields.mdqueries-and-operations.md

index.mddocs/

0

# Peewee

1

2

A 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.

3

4

## Package Information

5

6

- **Package Name**: peewee

7

- **Language**: Python

8

- **Installation**: `pip install peewee`

9

- **Version**: 3.18.2

10

- **License**: MIT

11

12

## Core Imports

13

14

```python

15

import peewee

16

```

17

18

Most common usage pattern:

19

20

```python

21

from peewee import *

22

```

23

24

Specific imports:

25

26

```python

27

from peewee import Model, CharField, IntegerField, SqliteDatabase

28

```

29

30

## Basic Usage

31

32

```python

33

from peewee import *

34

35

# Define database

36

db = SqliteDatabase('my_app.db')

37

38

# Define model

39

class User(Model):

40

username = CharField(unique=True)

41

email = CharField()

42

age = IntegerField()

43

44

class Meta:

45

database = db

46

47

# Create tables

48

db.create_tables([User])

49

50

# Create records

51

user = User.create(username='john', email='john@example.com', age=25)

52

53

# Query records

54

users = User.select().where(User.age > 18)

55

for user in users:

56

print(user.username, user.email)

57

58

# Update records

59

User.update(age=26).where(User.username == 'john').execute()

60

61

# Delete records

62

User.delete().where(User.age < 18).execute()

63

```

64

65

## Architecture

66

67

Peewee follows a simple architecture centered around a few key components:

68

69

- **Database**: Connection and transaction management for various backends (SQLite, PostgreSQL, MySQL)

70

- **Model**: Active Record pattern base class that maps to database tables

71

- **Field**: Type-safe column definitions with validation and conversion

72

- **Query**: Fluent query builder for SELECT, INSERT, UPDATE, DELETE operations

73

- **Schema**: DDL operations for table and index creation/management

74

75

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.

76

77

## Capabilities

78

79

### Models and Fields

80

81

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.

82

83

```python { .api }

84

class Model:

85

def save(self, force_insert=False, only=None): ...

86

def delete_instance(self, recursive=False, delete_nullable=False): ...

87

@classmethod

88

def create(cls, **kwargs): ...

89

@classmethod

90

def get(cls, *query, **filters): ...

91

@classmethod

92

def get_or_create(cls, **kwargs): ...

93

@classmethod

94

def select(cls, *fields): ...

95

@classmethod

96

def update(cls, **fields): ...

97

@classmethod

98

def delete(cls): ...

99

100

class Field:

101

def __init__(self, null=False, index=False, unique=False, column_name=None,

102

default=None, primary_key=False, constraints=None,

103

sequence=None, collation=None, unindexed=False, choices=None,

104

help_text=None, verbose_name=None, validators=None): ...

105

106

class ForeignKeyField(Field):

107

def __init__(self, model, field=None, backref=None, on_delete=None,

108

on_update=None, deferrable=None, lazy_load=True, **kwargs): ...

109

```

110

111

[Models and Fields](./models-and-fields.md)

112

113

### Database and Connections

114

115

Database connection management, transaction handling, and backend-specific functionality. Supports SQLite, PostgreSQL, MySQL, and connection proxying for multi-database scenarios.

116

117

```python { .api }

118

class Database:

119

def connect(self, reuse_if_open=False): ...

120

def close(self): ...

121

def execute_sql(self, sql, params=None, commit=None): ...

122

def begin(self): ...

123

def commit(self): ...

124

def rollback(self): ...

125

def atomic(self, *args, **kwargs): ...

126

def transaction(self, *args, **kwargs): ...

127

def create_tables(self, models, **options): ...

128

def drop_tables(self, models, **options): ...

129

130

class SqliteDatabase(Database): ...

131

class PostgresqlDatabase(Database): ...

132

class MySQLDatabase(Database): ...

133

class DatabaseProxy(Database): ...

134

```

135

136

[Database and Connections](./database-and-connections.md)

137

138

### Queries and Operations

139

140

Query building, filtering, joins, aggregation, and bulk operations. Provides a fluent interface for constructing complex SQL queries with Python syntax.

141

142

```python { .api }

143

class Select:

144

def where(self, *expressions): ...

145

def join(self, dest, join_type='INNER', on=None): ...

146

def group_by(self, *columns): ...

147

def having(self, *expressions): ...

148

def order_by(self, *columns): ...

149

def limit(self, limit, offset=0): ...

150

def distinct(self, distinct=True): ...

151

def aggregate(self, aggregation): ...

152

def count(self, clear_limit=False): ...

153

def exists(self): ...

154

def get(self): ...

155

156

def fn(*args, **kwargs): ... # Function call builder

157

class Case: ... # SQL CASE expressions

158

class SQL: ... # Raw SQL expressions

159

def prefetch(*args, **kwargs): ... # Prefetch related objects

160

```

161

162

[Queries and Operations](./queries-and-operations.md)

163

164

### Extensions (Playhouse)

165

166

Advanced database extensions, additional field types, connection pooling, database-specific features, and framework integrations provided by the playhouse package.

167

168

```python { .api }

169

# Database extensions

170

from playhouse.postgres_ext import PostgresqlExtDatabase, ArrayField, JSONField

171

from playhouse.sqlite_ext import SqliteExtDatabase, FTSModel, JSONField

172

from playhouse.mysql_ext import MySQLConnectorDatabase, JSONField

173

174

# Connection pooling

175

from playhouse.pool import PooledPostgresqlDatabase, PooledMySQLDatabase

176

177

# Utilities and integrations

178

from playhouse.shortcuts import model_to_dict, dict_to_model

179

from playhouse.migrate import migrate, PostgresqlMigrator

180

from playhouse.flask_utils import FlaskDB, get_object_or_404

181

from playhouse.dataset import DataSet

182

```

183

184

[Extensions (Playhouse)](./extensions-playhouse.md)

185

186

## Exception Handling

187

188

```python { .api }

189

class PeeweeException(Exception): ...

190

class ImproperlyConfigured(PeeweeException): ...

191

class DoesNotExist(PeeweeException): ...

192

class DatabaseError(PeeweeException): ...

193

class DataError(DatabaseError): ...

194

class IntegrityError(DatabaseError): ...

195

class InterfaceError(DatabaseError): ...

196

class InternalError(DatabaseError): ...

197

class NotSupportedError(DatabaseError): ...

198

class OperationalError(DatabaseError): ...

199

class ProgrammingError(DatabaseError): ...

200

```

201

202

Common exception handling patterns:

203

204

```python

205

from peewee import DoesNotExist, IntegrityError

206

207

try:

208

user = User.get(User.username == 'nonexistent')

209

except DoesNotExist:

210

print("User not found")

211

212

try:

213

User.create(username='duplicate', email='test@example.com')

214

except IntegrityError:

215

print("Username already exists")

216

```

217

218

## Version Information

219

220

```python { .api }

221

__version__ = '3.18.2'

222

```