0
# Models and Fields
1
2
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.
3
4
## Capabilities
5
6
### Model Definition
7
8
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.
9
10
```python { .api }
11
class Model:
12
"""
13
Base model class for all database models.
14
"""
15
def save(self, force_insert=False, only=None):
16
"""
17
Save the model instance to database.
18
19
Parameters:
20
- force_insert (bool): Force INSERT instead of UPDATE
21
- only (list): Only save specified fields
22
23
Returns:
24
int: Number of rows affected
25
"""
26
27
def delete_instance(self, recursive=False, delete_nullable=False):
28
"""
29
Delete this model instance from database.
30
31
Parameters:
32
- recursive (bool): Delete related objects
33
- delete_nullable (bool): Delete nullable related objects
34
35
Returns:
36
int: Number of rows deleted
37
"""
38
39
@classmethod
40
def create(cls, **kwargs):
41
"""
42
Create and save a new model instance.
43
44
Parameters:
45
- **kwargs: Field values for the new instance
46
47
Returns:
48
Model: The created instance
49
"""
50
51
@classmethod
52
def get(cls, *query, **filters):
53
"""
54
Get a single model instance matching the query.
55
56
Parameters:
57
- *query: Query expressions
58
- **filters: Field filters
59
60
Returns:
61
Model: The matching instance
62
63
Raises:
64
DoesNotExist: If no matching instance found
65
"""
66
67
@classmethod
68
def get_or_create(cls, **kwargs):
69
"""
70
Get existing instance or create new one.
71
72
Parameters:
73
- **kwargs: Field values to match or create with
74
75
Returns:
76
tuple: (instance, created) where created is bool
77
"""
78
79
@classmethod
80
def select(cls, *fields):
81
"""
82
Create a SELECT query for this model.
83
84
Parameters:
85
- *fields: Fields to select (defaults to all)
86
87
Returns:
88
Select: Query instance
89
"""
90
91
@classmethod
92
def update(cls, **fields):
93
"""
94
Create an UPDATE query for this model.
95
96
Parameters:
97
- **fields: Field values to update
98
99
Returns:
100
Update: Query instance
101
"""
102
103
@classmethod
104
def delete(cls):
105
"""
106
Create a DELETE query for this model.
107
108
Returns:
109
Delete: Query instance
110
"""
111
112
@classmethod
113
def create_table(cls, fail_silently=False):
114
"""
115
Create the database table for this model.
116
117
Parameters:
118
- fail_silently (bool): Don't raise error if table exists
119
"""
120
121
@classmethod
122
def drop_table(cls, fail_silently=False, cascade=False):
123
"""
124
Drop the database table for this model.
125
126
Parameters:
127
- fail_silently (bool): Don't raise error if table doesn't exist
128
- cascade (bool): Drop dependent objects
129
"""
130
131
@classmethod
132
def truncate_table(cls, restart_identity=False, cascade=False):
133
"""
134
Truncate the database table for this model.
135
136
Parameters:
137
- restart_identity (bool): Restart sequence counters
138
- cascade (bool): Truncate dependent tables
139
"""
140
141
class CompositeKey:
142
"""
143
Support for composite primary keys across multiple fields.
144
"""
145
def __init__(self, *field_names):
146
"""
147
Parameters:
148
- *field_names: Names of fields forming the composite key
149
"""
150
```
151
152
Usage example:
153
154
```python
155
from peewee import *
156
157
db = SqliteDatabase('example.db')
158
159
class User(Model):
160
username = CharField(unique=True)
161
email = CharField()
162
is_active = BooleanField(default=True)
163
164
class Meta:
165
database = db
166
table_name = 'users'
167
indexes = (
168
(('username', 'email'), True), # Unique index
169
)
170
171
# Create and save instance
172
user = User.create(username='john', email='john@example.com')
173
174
# Get instance
175
user = User.get(User.username == 'john')
176
177
# Update instance
178
user.email = 'newemail@example.com'
179
user.save()
180
181
# Delete instance
182
user.delete_instance()
183
```
184
185
### Field Types
186
187
Base field class and all available field types for database column definitions. Fields provide type safety, validation, and database-specific conversion.
188
189
```python { .api }
190
class Field:
191
"""
192
Base class for all field types.
193
"""
194
def __init__(self, null=False, index=False, unique=False, column_name=None,
195
default=None, primary_key=False, constraints=None,
196
sequence=None, collation=None, unindexed=False, choices=None,
197
help_text=None, verbose_name=None, validators=None):
198
"""
199
Parameters:
200
- null (bool): Allow NULL values
201
- index (bool): Create database index
202
- unique (bool): Enforce uniqueness constraint
203
- column_name (str): Custom column name
204
- default: Default value or callable
205
- primary_key (bool): Make field primary key
206
- constraints (list): Additional SQL constraints
207
- sequence (str): Database sequence name
208
- collation (str): String collation
209
- unindexed (bool): Disable indexing for this field
210
- choices (list): Valid choices for field
211
- help_text (str): Documentation text
212
- verbose_name (str): Human-readable name
213
- validators (list): Validation functions
214
"""
215
216
class AnyField(Field):
217
"""Field that accepts any data type without conversion."""
218
219
class BareField(Field):
220
"""Raw field with no type conversion logic."""
221
222
# Integer Fields
223
class IntegerField(Field):
224
"""Standard 32-bit integer field."""
225
226
class BigIntegerField(Field):
227
"""64-bit integer field for large numbers."""
228
229
class SmallIntegerField(Field):
230
"""16-bit integer field for small numbers."""
231
232
class AutoField(Field):
233
"""Auto-incrementing integer primary key."""
234
235
class BigAutoField(Field):
236
"""Auto-incrementing 64-bit integer primary key."""
237
238
class IdentityField(Field):
239
"""PostgreSQL identity column with auto-generation."""
240
241
class PrimaryKeyField(AutoField):
242
"""Deprecated auto-incrementing primary key (use AutoField)."""
243
244
# Numeric Fields
245
class FloatField(Field):
246
"""Single-precision floating-point field."""
247
248
class DoubleField(Field):
249
"""Double-precision floating-point field."""
250
251
class DecimalField(Field):
252
"""
253
Fixed-precision decimal field for financial data.
254
255
Parameters:
256
- max_digits (int): Maximum total digits
257
- decimal_places (int): Decimal places
258
- auto_round (bool): Automatically round values
259
- rounding (str): Rounding mode
260
"""
261
262
# String Fields
263
class CharField(Field):
264
"""
265
Variable-length character field.
266
267
Parameters:
268
- max_length (int): Maximum string length
269
"""
270
271
class FixedCharField(CharField):
272
"""Fixed-length character field, padded if necessary."""
273
274
class TextField(Field):
275
"""Large text field for unlimited text storage."""
276
277
# Binary Fields
278
class BlobField(Field):
279
"""Binary large object field for file data."""
280
281
class BitField(Field):
282
"""
283
Bit field for storing boolean flags efficiently.
284
285
Parameters:
286
- flags (dict): Named flags mapping
287
"""
288
289
class BigBitField(BitField):
290
"""Large bit field for many boolean flags."""
291
292
# Date/Time Fields
293
class DateField(Field):
294
"""
295
Date field (YYYY-MM-DD format).
296
297
Parameters:
298
- formats (list): Accepted date formats
299
"""
300
301
class TimeField(Field):
302
"""
303
Time field (HH:MM:SS format).
304
305
Parameters:
306
- formats (list): Accepted time formats
307
"""
308
309
class DateTimeField(Field):
310
"""
311
Combined date and time field.
312
313
Parameters:
314
- formats (list): Accepted datetime formats
315
"""
316
317
class TimestampField(BigIntegerField):
318
"""
319
Unix timestamp field with configurable resolution.
320
321
Parameters:
322
- resolution (int): Timestamp resolution (1=seconds, 1000=milliseconds, etc.)
323
- utc (bool): Use UTC time for default values
324
"""
325
326
# Special Fields
327
class BooleanField(Field):
328
"""Boolean true/false field."""
329
330
class UUIDField(Field):
331
"""UUID field for unique identifiers."""
332
333
class BinaryUUIDField(UUIDField):
334
"""Binary UUID field for space efficiency."""
335
336
class IPField(BigIntegerField):
337
"""IPv4 address field stored as 32-bit integer."""
338
```
339
340
Usage examples:
341
342
```python
343
class Product(Model):
344
name = CharField(max_length=100)
345
description = TextField()
346
price = DecimalField(max_digits=10, decimal_places=2)
347
created_at = DateTimeField(default=datetime.datetime.now)
348
is_active = BooleanField(default=True)
349
tags = BitField() # For feature flags
350
351
class Meta:
352
database = db
353
```
354
355
### Relationship Fields
356
357
Foreign key and many-to-many relationship fields for modeling database relationships between tables.
358
359
```python { .api }
360
class ForeignKeyField(Field):
361
"""
362
Foreign key relationship to another model.
363
"""
364
def __init__(self, model, field=None, backref=None, on_delete=None,
365
on_update=None, deferrable=None, lazy_load=True, **kwargs):
366
"""
367
Parameters:
368
- model: Target model class or string name
369
- field: Target field (defaults to primary key)
370
- backref (str): Name for reverse relationship
371
- on_delete (str): Cascade behavior ('CASCADE', 'SET NULL', etc.)
372
- on_update (str): Update cascade behavior
373
- deferrable (str): Deferrable constraint mode
374
- lazy_load (bool): Enable lazy loading
375
- **kwargs: Additional Field parameters
376
"""
377
378
class ManyToManyField(Field):
379
"""
380
Many-to-many relationship through intermediate table.
381
"""
382
def __init__(self, model, backref=None, through_model=None, **kwargs):
383
"""
384
Parameters:
385
- model: Target model class
386
- backref (str): Name for reverse relationship
387
- through_model: Custom intermediate model
388
- **kwargs: Additional Field parameters
389
"""
390
391
class DeferredForeignKey(Field):
392
"""
393
Deferred foreign key for circular references.
394
"""
395
def __init__(self, rel_model_name, **kwargs):
396
"""
397
Parameters:
398
- rel_model_name (str): Name of target model
399
- **kwargs: ForeignKeyField parameters
400
"""
401
```
402
403
Usage examples:
404
405
```python
406
class User(Model):
407
username = CharField(unique=True)
408
email = CharField()
409
410
class Meta:
411
database = db
412
413
class Post(Model):
414
title = CharField()
415
content = TextField()
416
author = ForeignKeyField(User, backref='posts')
417
created_at = DateTimeField(default=datetime.datetime.now)
418
419
class Meta:
420
database = db
421
422
class Tag(Model):
423
name = CharField()
424
425
class Meta:
426
database = db
427
428
class PostTag(Model):
429
post = ForeignKeyField(Post)
430
tag = ForeignKeyField(Tag)
431
432
class Meta:
433
database = db
434
primary_key = CompositeKey('post', 'tag')
435
436
# Many-to-many through intermediate model
437
Post.tags = ManyToManyField(Tag, backref='posts', through_model=PostTag)
438
439
# Usage
440
user = User.create(username='john', email='john@example.com')
441
post = Post.create(title='Hello', content='World', author=user)
442
443
# Access relationships
444
print(f"Post author: {post.author.username}")
445
print(f"User posts: {list(user.posts)}")
446
```
447
448
### Model Meta Options
449
450
Configuration options for model behavior, database table settings, and constraints.
451
452
```python
453
class Model:
454
class Meta:
455
"""
456
Model metadata configuration.
457
"""
458
database = None # Database instance
459
table_name = None # Custom table name
460
indexes = () # Index definitions
461
primary_key = None # Composite primary key
462
constraints = () # Table constraints
463
schema = None # Database schema
464
only_save_dirty = False # Only save changed fields
465
legacy_table_names = False # Use legacy naming
466
depends_on = () # Model dependencies
467
without_rowid = False # SQLite WITHOUT ROWID
468
strict_tables = False # SQLite STRICT tables
469
table_function = False # Table-valued function
470
temporary = False # Temporary table
471
```
472
473
## Model Validation
474
475
```python { .api }
476
class Model:
477
def validate(self, field_dict=None, exclude=None):
478
"""
479
Validate model instance.
480
481
Parameters:
482
- field_dict (dict): Override field values
483
- exclude (list): Fields to exclude from validation
484
485
Raises:
486
ValidationError: If validation fails
487
"""
488
489
def is_dirty(self):
490
"""
491
Check if model has unsaved changes.
492
493
Returns:
494
bool: True if model has changes
495
"""
496
497
def dirty_fields(self):
498
"""
499
Get list of fields with unsaved changes.
500
501
Returns:
502
list: Modified field names
503
"""
504
```
505
506
## Field Validation
507
508
Custom field validation with validators:
509
510
```python
511
from peewee import *
512
513
def validate_email(value):
514
if '@' not in value:
515
raise ValueError('Invalid email format')
516
517
class User(Model):
518
email = CharField(validators=[validate_email])
519
age = IntegerField(constraints=[Check('age >= 0')])
520
521
class Meta:
522
database = db
523
```