0
# Database Transactions
1
2
Django's transaction system provides database transaction management with atomic operations, savepoints, and commit/rollback functionality for ensuring data consistency and integrity.
3
4
## Core Imports
5
6
```python
7
# Transaction management
8
from django.db import transaction
9
10
# Transaction functions
11
from django.db.transaction import (
12
atomic, commit, rollback,
13
savepoint, savepoint_commit, savepoint_rollback,
14
get_autocommit, set_autocommit,
15
get_rollback, set_rollback,
16
on_commit, mark_for_rollback_on_error
17
)
18
19
# Transaction exceptions
20
from django.db.transaction import TransactionManagementError
21
```
22
23
## Capabilities
24
25
### Atomic Transactions
26
27
The atomic decorator and context manager for ensuring database operations execute as a single transaction.
28
29
```python { .api }
30
class Atomic:
31
"""
32
Context manager and decorator for atomic database operations.
33
34
Can be used as decorator or context manager to ensure all database
35
operations within the block execute atomically.
36
"""
37
using: str | None
38
savepoint: bool
39
40
def __init__(self, using: str | None, savepoint: bool, durable: bool) -> None: ...
41
def __call__(self, func: Callable) -> Callable: ...
42
def __enter__(self) -> None: ...
43
def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None) -> None: ...
44
45
def atomic(using: str | None = None, savepoint: bool = True, durable: bool = False) -> Atomic:
46
"""
47
Create atomic transaction block.
48
49
Args:
50
using: Database alias to use for transaction
51
savepoint: Whether to create savepoint for nested transactions
52
durable: Whether to ensure transaction durability
53
54
Returns:
55
Atomic context manager/decorator
56
"""
57
```
58
59
**Usage Examples:**
60
61
```python
62
# As decorator
63
@transaction.atomic
64
def create_user_with_profile(user_data, profile_data):
65
user = User.objects.create(**user_data)
66
Profile.objects.create(user=user, **profile_data)
67
return user
68
69
# As context manager
70
def transfer_funds(from_account, to_account, amount):
71
with transaction.atomic():
72
from_account.balance -= amount
73
from_account.save()
74
to_account.balance += amount
75
to_account.save()
76
77
# With specific database
78
with transaction.atomic(using='db_alias'):
79
# Operations on specific database
80
pass
81
```
82
83
### Transaction Control
84
85
Functions for explicit transaction management and control.
86
87
```python { .api }
88
def commit(using: str | None = None) -> None:
89
"""
90
Commit the current transaction.
91
92
Args:
93
using: Database alias to commit transaction on
94
"""
95
96
def rollback(using: str | None = None) -> None:
97
"""
98
Roll back the current transaction.
99
100
Args:
101
using: Database alias to rollback transaction on
102
"""
103
104
def get_autocommit(using: str | None = None) -> bool:
105
"""
106
Get autocommit mode for database connection.
107
108
Args:
109
using: Database alias
110
111
Returns:
112
Current autocommit setting
113
"""
114
115
def set_autocommit(autocommit: bool, using: str | None = None) -> None:
116
"""
117
Set autocommit mode for database connection.
118
119
Args:
120
autocommit: Whether to enable autocommit
121
using: Database alias
122
"""
123
124
def get_rollback(using: str | None = None) -> bool:
125
"""
126
Get rollback flag for current transaction.
127
128
Args:
129
using: Database alias
130
131
Returns:
132
Whether transaction is marked for rollback
133
"""
134
135
def set_rollback(rollback: bool, using: str | None = None) -> None:
136
"""
137
Mark current transaction for rollback.
138
139
Args:
140
rollback: Whether to mark for rollback
141
using: Database alias
142
"""
143
```
144
145
### Savepoints
146
147
Functions for managing transaction savepoints for nested transactions.
148
149
```python { .api }
150
def savepoint(using: str | None = None) -> str:
151
"""
152
Create a transaction savepoint.
153
154
Args:
155
using: Database alias
156
157
Returns:
158
Savepoint identifier
159
"""
160
161
def savepoint_commit(sid: str, using: str | None = None) -> None:
162
"""
163
Commit a transaction savepoint.
164
165
Args:
166
sid: Savepoint identifier
167
using: Database alias
168
"""
169
170
def savepoint_rollback(sid: str, using: str | None = None) -> None:
171
"""
172
Rollback to a transaction savepoint.
173
174
Args:
175
sid: Savepoint identifier
176
using: Database alias
177
"""
178
179
def clean_savepoints(using: str | None = None) -> None:
180
"""
181
Clean all savepoints for current transaction.
182
183
Args:
184
using: Database alias
185
"""
186
```
187
188
**Usage Examples:**
189
190
```python
191
def complex_operation():
192
with transaction.atomic():
193
# Main transaction
194
create_user()
195
196
# Create savepoint for risky operation
197
sid = transaction.savepoint()
198
try:
199
risky_operation()
200
transaction.savepoint_commit(sid)
201
except Exception:
202
transaction.savepoint_rollback(sid)
203
# Continue with main transaction
204
```
205
206
### Post-Commit Hooks
207
208
Functions for executing code after transaction commit.
209
210
```python { .api }
211
def on_commit(func: Callable[[], object], using: str | None = None, robust: bool = True) -> None:
212
"""
213
Register function to run after current transaction commits.
214
215
Args:
216
func: Function to execute after commit
217
using: Database alias
218
robust: Whether to catch and log exceptions from func
219
"""
220
```
221
222
**Usage Examples:**
223
224
```python
225
def send_welcome_email(user_id):
226
user = User.objects.get(id=user_id)
227
send_email(user.email, 'Welcome!')
228
229
def create_user(email, password):
230
with transaction.atomic():
231
user = User.objects.create(email=email, password=password)
232
# Email only sent if transaction commits successfully
233
transaction.on_commit(lambda: send_welcome_email(user.id))
234
return user
235
```
236
237
### Error Handling
238
239
Context manager for handling errors within transactions.
240
241
```python { .api }
242
def mark_for_rollback_on_error(using: str | None = None) -> Iterator[None]:
243
"""
244
Context manager that marks transaction for rollback on any exception.
245
246
Args:
247
using: Database alias
248
249
Yields:
250
None
251
"""
252
```
253
254
**Usage Examples:**
255
256
```python
257
with transaction.atomic():
258
with transaction.mark_for_rollback_on_error():
259
# Any exception here will mark transaction for rollback
260
potentially_failing_operation()
261
# Transaction continues but will be rolled back
262
```
263
264
### Non-Atomic Requests
265
266
Decorator to disable automatic transaction wrapping for views.
267
268
```python { .api }
269
def non_atomic_requests(using: str | None = None) -> Callable:
270
"""
271
Decorator to disable atomic request handling for views.
272
273
Args:
274
using: Database alias
275
276
Returns:
277
Decorator function
278
"""
279
```
280
281
**Usage Examples:**
282
283
```python
284
from django.db import transaction
285
286
@transaction.non_atomic_requests
287
def my_view(request):
288
# This view won't be wrapped in automatic transaction
289
pass
290
291
# For specific database
292
@transaction.non_atomic_requests(using='read_only_db')
293
def read_only_view(request):
294
pass
295
```
296
297
### Transaction Exceptions
298
299
```python { .api }
300
class TransactionManagementError(ProgrammingError):
301
"""
302
Exception raised for transaction management errors.
303
304
Indicates improper use of transaction management functions
305
or invalid transaction state.
306
"""
307
```
308
309
## Advanced Usage Patterns
310
311
**Nested Transactions with Savepoints:**
312
313
```python
314
def complex_business_operation():
315
with transaction.atomic(): # Outer transaction
316
step_one()
317
318
with transaction.atomic(): # Inner savepoint
319
step_two() # If this fails, only step_two is rolled back
320
321
step_three() # This still executes
322
```
323
324
**Database-Specific Transactions:**
325
326
```python
327
def multi_database_operation():
328
with transaction.atomic(using='primary'):
329
# Operations on primary database
330
primary_operation()
331
332
with transaction.atomic(using='analytics'):
333
# Operations on analytics database
334
analytics_operation()
335
```
336
337
**Conditional Rollback:**
338
339
```python
340
def conditional_operation():
341
with transaction.atomic():
342
result = risky_operation()
343
if not result.is_valid():
344
transaction.set_rollback(True)
345
```