0
# Database and ORM
1
2
Django's Object-Relational Mapping (ORM) system provides a Python interface for database operations, enabling type-safe database queries, model definitions, and relationship management.
3
4
## Core Imports
5
6
```python
7
# Model base class and fields
8
from django.db import models
9
from django.db.models import Model, Manager, QuerySet
10
11
# Field types
12
from django.db.models import (
13
CharField, TextField, IntegerField, PositiveIntegerField,
14
FloatField, DecimalField, BooleanField, DateField, DateTimeField,
15
TimeField, EmailField, URLField, SlugField, UUIDField,
16
ForeignKey, OneToOneField, ManyToManyField,
17
FileField, ImageField, JSONField
18
)
19
20
# Query functions and aggregation
21
from django.db.models import (
22
Q, F, Value, Count, Sum, Avg, Max, Min,
23
Exists, OuterRef, Subquery, Case, When
24
)
25
26
# Database operations
27
from django.db import transaction, connection
28
from django.db.models.signals import pre_save, post_save, pre_delete, post_delete
29
```
30
31
## Capabilities
32
33
### Model Base Class
34
35
The fundamental base class for all Django models, providing database table mapping and ORM functionality.
36
37
```python { .api }
38
class Model:
39
"""
40
Base class for all Django models.
41
42
Provides database table mapping, field definitions, and ORM methods.
43
"""
44
pk: Any # Primary key field
45
objects: Manager # Default manager
46
47
def save(self, force_insert: bool = False, force_update: bool = False, using: str = None, update_fields: list = None) -> None: ...
48
def delete(self, using: str = None, keep_parents: bool = False) -> tuple: ...
49
def refresh_from_db(self, using: str = None, fields: list = None) -> None: ...
50
def clean(self) -> None: ...
51
def full_clean(self, exclude: list = None, validate_unique: bool = True) -> None: ...
52
def validate_unique(self, exclude: list = None) -> None: ...
53
54
@classmethod
55
def from_db(cls, db: str, field_names: list, values: list): ...
56
```
57
58
### Manager and QuerySet
59
60
Database query interface providing lazy evaluation and chainable query operations.
61
62
```python { .api }
63
class Manager:
64
"""
65
Default manager for model database operations.
66
"""
67
def get_queryset(self) -> QuerySet: ...
68
def all(self) -> QuerySet: ...
69
def filter(self, *args, **kwargs) -> QuerySet: ...
70
def exclude(self, *args, **kwargs) -> QuerySet: ...
71
def get(self, *args, **kwargs): ...
72
def create(self, **kwargs): ...
73
def get_or_create(self, defaults: dict = None, **kwargs) -> tuple: ...
74
def update_or_create(self, defaults: dict = None, **kwargs) -> tuple: ...
75
def bulk_create(self, objs: list, batch_size: int = None, ignore_conflicts: bool = False, update_conflicts: bool = False, update_fields: list = None, unique_fields: list = None) -> list: ...
76
def bulk_update(self, objs: list, fields: list, batch_size: int = None) -> int: ...
77
def count(self) -> int: ...
78
def exists(self) -> bool: ...
79
def delete(self) -> tuple: ...
80
def update(self, **kwargs) -> int: ...
81
82
class QuerySet:
83
"""
84
Lazy database query object supporting chaining and evaluation.
85
"""
86
def filter(self, *args, **kwargs) -> QuerySet: ...
87
def exclude(self, *args, **kwargs) -> QuerySet: ...
88
def annotate(self, *args, **kwargs) -> QuerySet: ...
89
def order_by(self, *field_names) -> QuerySet: ...
90
def reverse(self) -> QuerySet: ...
91
def distinct(self, *field_names) -> QuerySet: ...
92
def values(self, *fields) -> QuerySet: ...
93
def values_list(self, *fields, flat: bool = False, named: bool = False) -> QuerySet: ...
94
def select_related(self, *fields) -> QuerySet: ...
95
def prefetch_related(self, *lookups) -> QuerySet: ...
96
def only(self, *fields) -> QuerySet: ...
97
def defer(self, *fields) -> QuerySet: ...
98
def aggregate(self, *args, **kwargs) -> dict: ...
99
def get(self, *args, **kwargs): ...
100
def first(self): ...
101
def last(self): ...
102
def earliest(self, *fields): ...
103
def latest(self, *fields): ...
104
def count(self) -> int: ...
105
def exists(self) -> bool: ...
106
def delete(self) -> tuple: ...
107
def update(self, **kwargs) -> int: ...
108
def iterator(self, chunk_size: int = 2000): ...
109
```
110
111
### Basic Field Types
112
113
Core field types for model definitions with appropriate type annotations.
114
115
```python { .api }
116
class Field:
117
"""Base field class for all model fields."""
118
def __init__(self, verbose_name: str = None, name: str = None, primary_key: bool = False,
119
max_length: int = None, unique: bool = False, blank: bool = False,
120
null: bool = False, db_index: bool = False, default=None,
121
editable: bool = True, help_text: str = '', choices=None, **kwargs): ...
122
123
class AutoField(Field):
124
"""Auto-incrementing integer field."""
125
def __init__(self, **kwargs): ...
126
127
class BigAutoField(Field):
128
"""64-bit auto-incrementing integer field."""
129
def __init__(self, **kwargs): ...
130
131
class BigIntegerField(Field):
132
"""64-bit integer field."""
133
def __init__(self, **kwargs): ...
134
135
class BinaryField(Field):
136
"""Binary data field."""
137
def __init__(self, max_length: int = None, **kwargs): ...
138
139
class BooleanField(Field):
140
"""Boolean field."""
141
def __init__(self, **kwargs): ...
142
143
class CharField(Field):
144
"""Character/string field with maximum length."""
145
def __init__(self, max_length: int, **kwargs): ...
146
147
class DateField(Field):
148
"""Date field."""
149
def __init__(self, auto_now: bool = False, auto_now_add: bool = False, **kwargs): ...
150
151
class DateTimeField(Field):
152
"""Date and time field."""
153
def __init__(self, auto_now: bool = False, auto_now_add: bool = False, **kwargs): ...
154
155
class DecimalField(Field):
156
"""Decimal number field with fixed precision."""
157
def __init__(self, max_digits: int, decimal_places: int, **kwargs): ...
158
159
class DurationField(Field):
160
"""Duration/timedelta field."""
161
def __init__(self, **kwargs): ...
162
163
class EmailField(CharField):
164
"""Email address field with validation."""
165
def __init__(self, max_length: int = 254, **kwargs): ...
166
167
class FileField(Field):
168
"""File upload field."""
169
def __init__(self, upload_to: str = '', storage=None, **kwargs): ...
170
171
class FloatField(Field):
172
"""Floating point number field."""
173
def __init__(self, **kwargs): ...
174
175
class ImageField(FileField):
176
"""Image file field with validation."""
177
def __init__(self, upload_to: str = '', height_field: str = None, width_field: str = None, **kwargs): ...
178
179
class IntegerField(Field):
180
"""Integer field."""
181
def __init__(self, **kwargs): ...
182
183
class JSONField(Field):
184
"""JSON data field."""
185
def __init__(self, encoder=None, decoder=None, **kwargs): ...
186
187
class PositiveBigIntegerField(Field):
188
"""Positive 64-bit integer field."""
189
def __init__(self, **kwargs): ...
190
191
class PositiveIntegerField(Field):
192
"""Positive integer field."""
193
def __init__(self, **kwargs): ...
194
195
class PositiveSmallIntegerField(Field):
196
"""Positive small integer field."""
197
def __init__(self, **kwargs): ...
198
199
class SlugField(CharField):
200
"""URL slug field."""
201
def __init__(self, max_length: int = 50, **kwargs): ...
202
203
class SmallAutoField(Field):
204
"""Small auto-incrementing integer field."""
205
def __init__(self, **kwargs): ...
206
207
class SmallIntegerField(Field):
208
"""Small integer field."""
209
def __init__(self, **kwargs): ...
210
211
class TextField(Field):
212
"""Large text field."""
213
def __init__(self, **kwargs): ...
214
215
class TimeField(Field):
216
"""Time field."""
217
def __init__(self, auto_now: bool = False, auto_now_add: bool = False, **kwargs): ...
218
219
class URLField(CharField):
220
"""URL field with validation."""
221
def __init__(self, max_length: int = 200, **kwargs): ...
222
223
class UUIDField(Field):
224
"""UUID field."""
225
def __init__(self, **kwargs): ...
226
```
227
228
### Relationship Fields
229
230
Fields that define relationships between models.
231
232
```python { .api }
233
class ForeignKey(Field):
234
"""Foreign key relationship to another model."""
235
def __init__(self, to, on_delete, related_name: str = None, related_query_name: str = None,
236
limit_choices_to=None, parent_link: bool = False, to_field: str = None,
237
db_constraint: bool = True, **kwargs): ...
238
239
class ManyToManyField(Field):
240
"""Many-to-many relationship."""
241
def __init__(self, to, related_name: str = None, related_query_name: str = None,
242
limit_choices_to=None, symmetrical: bool = None, through: str = None,
243
through_fields: tuple = None, db_constraint: bool = True,
244
db_table: str = None, **kwargs): ...
245
246
class OneToOneField(ForeignKey):
247
"""One-to-one relationship."""
248
def __init__(self, to, on_delete, parent_link: bool = False, **kwargs): ...
249
250
class ForeignObject(Field):
251
"""Generic foreign object for advanced relationships."""
252
def __init__(self, to, on_delete, from_fields: list, to_fields: list, **kwargs): ...
253
```
254
255
### Deletion Behaviors
256
257
Constants defining behavior when related objects are deleted.
258
259
```python { .api }
260
CASCADE: Any # Delete related objects
261
PROTECT: Any # Prevent deletion if related objects exist
262
RESTRICT: Any # Restrict deletion
263
SET_NULL: Any # Set foreign key to NULL
264
SET_DEFAULT: Any # Set foreign key to default value
265
DO_NOTHING: Any # Take no action
266
267
class ProtectedError(Exception):
268
"""Raised when trying to delete a protected object."""
269
270
class RestrictedError(Exception):
271
"""Raised when deletion is restricted."""
272
```
273
274
### Query Expressions
275
276
Objects for building complex database queries and expressions.
277
278
```python { .api }
279
class Q:
280
"""Query object for complex lookups."""
281
def __init__(self, *args, **kwargs): ...
282
def __and__(self, other): ...
283
def __or__(self, other): ...
284
def __invert__(self): ...
285
286
class F:
287
"""Field reference for database-level operations."""
288
def __init__(self, name: str): ...
289
def __add__(self, other): ...
290
def __sub__(self, other): ...
291
def __mul__(self, other): ...
292
def __truediv__(self, other): ...
293
def __mod__(self, other): ...
294
def __pow__(self, other): ...
295
296
class Value:
297
"""Literal value in database expressions."""
298
def __init__(self, value, output_field=None): ...
299
300
class Case:
301
"""Conditional database expression."""
302
def __init__(self, *cases, default=None, output_field=None): ...
303
304
class When:
305
"""Condition for Case expressions."""
306
def __init__(self, condition=None, then=None, **lookups): ...
307
308
class Exists:
309
"""EXISTS subquery expression."""
310
def __init__(self, queryset, negated: bool = False): ...
311
312
class Subquery:
313
"""Subquery expression."""
314
def __init__(self, queryset, output_field=None): ...
315
316
class OuterRef:
317
"""Reference to outer query in subqueries."""
318
def __init__(self, name: str): ...
319
320
class Func:
321
"""Database function call."""
322
def __init__(self, *expressions, output_field=None, **extra): ...
323
324
class Window:
325
"""Window function expression."""
326
def __init__(self, expression, partition_by=None, order_by=None, frame=None, output_field=None): ...
327
```
328
329
### Aggregates
330
331
Functions for aggregating database values.
332
333
```python { .api }
334
class Aggregate:
335
"""Base class for aggregate functions."""
336
def __init__(self, *expressions, output_field=None, is_summary: bool = False, **extra): ...
337
338
class Avg(Aggregate):
339
"""Average aggregate function."""
340
341
class Count(Aggregate):
342
"""Count aggregate function."""
343
def __init__(self, expression, distinct: bool = False, **extra): ...
344
345
class Max(Aggregate):
346
"""Maximum value aggregate function."""
347
348
class Min(Aggregate):
349
"""Minimum value aggregate function."""
350
351
class StdDev(Aggregate):
352
"""Standard deviation aggregate function."""
353
def __init__(self, expression, sample: bool = False, **extra): ...
354
355
class Sum(Aggregate):
356
"""Sum aggregate function."""
357
358
class Variance(Aggregate):
359
"""Variance aggregate function."""
360
def __init__(self, expression, sample: bool = False, **extra): ...
361
```
362
363
### Database Constraints
364
365
Constraints for ensuring data integrity at the database level.
366
367
```python { .api }
368
class BaseConstraint:
369
"""Base class for database constraints."""
370
def __init__(self, name: str): ...
371
372
class CheckConstraint(BaseConstraint):
373
"""Check constraint for validating field values."""
374
def __init__(self, check, name: str): ...
375
376
class UniqueConstraint(BaseConstraint):
377
"""Unique constraint across multiple fields."""
378
def __init__(self, fields: list, name: str, condition=None, deferrable=None, include=None, opclasses=None): ...
379
380
class Deferrable:
381
"""Deferrable constraint options."""
382
DEFERRED: str
383
IMMEDIATE: str
384
```
385
386
### Database Indexes
387
388
Index definitions for query optimization.
389
390
```python { .api }
391
class Index:
392
"""Database index definition."""
393
def __init__(self, fields: list, name: str = None, db_tablespace: str = None,
394
opclasses: list = None, condition=None, include: list = None): ...
395
```
396
397
### Prefetch Operations
398
399
Optimized loading of related objects.
400
401
```python { .api }
402
class Prefetch:
403
"""Prefetch definition for select_related optimization."""
404
def __init__(self, lookup: str, queryset=None, to_attr: str = None): ...
405
406
def prefetch_related_objects(model_instances: list, *related_lookups) -> None:
407
"""Prefetch related objects for a list of model instances."""
408
```
409
410
### Database Configuration
411
412
Database connection and routing configuration.
413
414
```python { .api }
415
connections: ConnectionHandler # Database connections
416
connection: BaseDatabaseWrapper # Default database connection
417
router: ConnectionRouter # Database routing
418
419
DEFAULT_DB_ALIAS: str # Default database alias name
420
421
def close_old_connections() -> None:
422
"""Close database connections that have become unusable."""
423
424
def reset_queries() -> None:
425
"""Reset the list of queries logged for the current connection."""
426
```
427
428
### Database Exceptions
429
430
Exceptions for database operations and integrity constraints.
431
432
```python { .api }
433
class Error(Exception):
434
"""Base database exception."""
435
436
class DatabaseError(Error):
437
"""Database-related error."""
438
439
class DataError(DatabaseError):
440
"""Data-related database error."""
441
442
class IntegrityError(DatabaseError):
443
"""Database integrity constraint violation."""
444
445
class InterfaceError(DatabaseError):
446
"""Database interface error."""
447
448
class InternalError(DatabaseError):
449
"""Database internal error."""
450
451
class NotSupportedError(DatabaseError):
452
"""Database operation not supported."""
453
454
class OperationalError(DatabaseError):
455
"""Database operational error."""
456
457
class ProgrammingError(DatabaseError):
458
"""Database programming error."""
459
```
460
461
### Model Utilities
462
463
Utility functions and constants for model operations.
464
465
```python { .api }
466
NOT_PROVIDED: Any # Sentinel for field defaults
467
468
class FieldDoesNotExist(Exception):
469
"""Raised when accessing non-existent model field."""
470
471
def get_object_or_404(klass, *args, **kwargs):
472
"""Get object or raise Http404 if not found."""
473
474
def get_list_or_404(klass, *args, **kwargs):
475
"""Get object list or raise Http404 if empty."""
476
```
477
478
### Model Meta Options
479
480
Configuration options for model behavior and database table settings.
481
482
```python { .api }
483
class Options:
484
"""Model meta options configuration."""
485
abstract: bool
486
app_label: str
487
base_manager_name: str
488
db_table: str
489
db_tablespace: str
490
default_manager_name: str
491
default_related_name: str
492
get_latest_by: str
493
managed: bool
494
order_with_respect_to: str
495
ordering: list
496
permissions: list
497
default_permissions: list
498
proxy: bool
499
required_db_features: list
500
required_db_vendor: str
501
select_on_save: bool
502
indexes: list
503
unique_together: list
504
index_together: list
505
constraints: list
506
verbose_name: str
507
verbose_name_plural: str
508
```