4
Django handles transactions in three different ways. The default is to commit
5
each transaction upon a write, but you can decorate a function to get
6
commit-on-success behavior. Alternatively, you can manage the transaction
10
from django.db import models
12
class Reporter(models.Model):
13
first_name = models.CharField(maxlength=30)
14
last_name = models.CharField(maxlength=30)
15
email = models.EmailField()
18
return "%s %s" % (self.first_name, self.last_name)
21
>>> from django.db import connection, transaction
23
# the default behavior is to autocommit after each save() action
24
>>> def create_a_reporter_then_fail(first, last):
25
... a = Reporter(first_name=first, last_name=last)
27
... raise Exception("I meant to do that")
29
>>> create_a_reporter_then_fail("Alice", "Smith")
30
Traceback (most recent call last):
32
Exception: I meant to do that
34
# The object created before the exception still exists
35
>>> Reporter.objects.all()
38
# the autocommit decorator works exactly the same as the default behavior
39
>>> autocomitted_create_then_fail = transaction.autocommit(create_a_reporter_then_fail)
40
>>> autocomitted_create_then_fail("Ben", "Jones")
41
Traceback (most recent call last):
43
Exception: I meant to do that
45
# Same behavior as before
46
>>> Reporter.objects.all()
47
[Alice Smith, Ben Jones]
49
# With the commit_on_success decorator, the transaction is only comitted if the
50
# function doesn't throw an exception
51
>>> committed_on_success = transaction.commit_on_success(create_a_reporter_then_fail)
52
>>> committed_on_success("Carol", "Doe")
53
Traceback (most recent call last):
55
Exception: I meant to do that
57
# This time the object never got saved
58
>>> Reporter.objects.all()
59
[Alice Smith, Ben Jones]
61
# If there aren't any exceptions, the data will get saved
62
>>> def remove_a_reporter():
63
... r = Reporter.objects.get(first_name="Alice")
66
>>> remove_comitted_on_success = transaction.commit_on_success(remove_a_reporter)
67
>>> remove_comitted_on_success()
68
>>> Reporter.objects.all()
71
# You can manually manage transactions if you really want to, but you
72
# have to remember to commit/rollback
73
>>> def manually_managed():
74
... r = Reporter(first_name="Carol", last_name="Doe")
76
... transaction.commit()
77
>>> manually_managed = transaction.commit_manually(manually_managed)
78
>>> manually_managed()
79
>>> Reporter.objects.all()
80
[Ben Jones, Carol Doe]
82
# If you forget, you'll get bad errors
83
>>> def manually_managed_mistake():
84
... r = Reporter(first_name="David", last_name="Davidson")
86
... # oops, I forgot to commit/rollback!
87
>>> manually_managed_mistake = transaction.commit_manually(manually_managed_mistake)
88
>>> manually_managed_mistake()
89
Traceback (most recent call last):
91
TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK
b'\\ No newline at end of file'