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
, DEFAULT_DB_ALIAS
12 class Reporter(models
.Model
):
13 first_name
= models
.CharField(max_length
=30)
14 last_name
= models
.CharField(max_length
=30)
15 email
= models
.EmailField()
18 ordering
= ('first_name', 'last_name')
20 def __unicode__(self
):
21 return u
"%s %s" % (self
.first_name
, self
.last_name
)
23 __test__
= {'API_TESTS':"""
24 >>> from django.db import connection, transaction
27 from django
.conf
import settings
29 building_docs
= getattr(settings
, 'BUILDING_DOCS', False)
31 if building_docs
or settings
.DATABASES
[DEFAULT_DB_ALIAS
]['ENGINE'] != 'django.db.backends.mysql':
32 __test__
['API_TESTS'] += """
33 # the default behavior is to autocommit after each save() action
34 >>> def create_a_reporter_then_fail(first, last):
35 ... a = Reporter(first_name=first, last_name=last)
37 ... raise Exception("I meant to do that")
39 >>> create_a_reporter_then_fail("Alice", "Smith")
40 Traceback (most recent call last):
42 Exception: I meant to do that
44 # The object created before the exception still exists
45 >>> Reporter.objects.all()
46 [<Reporter: Alice Smith>]
48 # the autocommit decorator works exactly the same as the default behavior
49 >>> autocomitted_create_then_fail = transaction.autocommit(create_a_reporter_then_fail)
50 >>> autocomitted_create_then_fail("Ben", "Jones")
51 Traceback (most recent call last):
53 Exception: I meant to do that
55 # Same behavior as before
56 >>> Reporter.objects.all()
57 [<Reporter: Alice Smith>, <Reporter: Ben Jones>]
59 # the autocommit decorator also works with a using argument
60 >>> using_autocomitted_create_then_fail = transaction.autocommit(using='default')(create_a_reporter_then_fail)
61 >>> using_autocomitted_create_then_fail("Carol", "Doe")
62 Traceback (most recent call last):
64 Exception: I meant to do that
66 # Same behavior as before
67 >>> Reporter.objects.all()
68 [<Reporter: Alice Smith>, <Reporter: Ben Jones>, <Reporter: Carol Doe>]
70 # With the commit_on_success decorator, the transaction is only committed if the
71 # function doesn't throw an exception
72 >>> committed_on_success = transaction.commit_on_success(create_a_reporter_then_fail)
73 >>> committed_on_success("Dirk", "Gently")
74 Traceback (most recent call last):
76 Exception: I meant to do that
78 # This time the object never got saved
79 >>> Reporter.objects.all()
80 [<Reporter: Alice Smith>, <Reporter: Ben Jones>, <Reporter: Carol Doe>]
82 # commit_on_success decorator also works with a using argument
83 >>> using_committed_on_success = transaction.commit_on_success(using='default')(create_a_reporter_then_fail)
84 >>> using_committed_on_success("Dirk", "Gently")
85 Traceback (most recent call last):
87 Exception: I meant to do that
89 # This time the object never got saved
90 >>> Reporter.objects.all()
91 [<Reporter: Alice Smith>, <Reporter: Ben Jones>, <Reporter: Carol Doe>]
93 # If there aren't any exceptions, the data will get saved
94 >>> def remove_a_reporter():
95 ... r = Reporter.objects.get(first_name="Alice")
98 >>> remove_comitted_on_success = transaction.commit_on_success(remove_a_reporter)
99 >>> remove_comitted_on_success()
100 >>> Reporter.objects.all()
101 [<Reporter: Ben Jones>, <Reporter: Carol Doe>]
103 # You can manually manage transactions if you really want to, but you
104 # have to remember to commit/rollback
105 >>> def manually_managed():
106 ... r = Reporter(first_name="Dirk", last_name="Gently")
108 ... transaction.commit()
109 >>> manually_managed = transaction.commit_manually(manually_managed)
110 >>> manually_managed()
111 >>> Reporter.objects.all()
112 [<Reporter: Ben Jones>, <Reporter: Carol Doe>, <Reporter: Dirk Gently>]
114 # If you forget, you'll get bad errors
115 >>> def manually_managed_mistake():
116 ... r = Reporter(first_name="Edward", last_name="Woodward")
118 ... # oops, I forgot to commit/rollback!
119 >>> manually_managed_mistake = transaction.commit_manually(manually_managed_mistake)
120 >>> manually_managed_mistake()
121 Traceback (most recent call last):
123 TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK
125 # commit_manually also works with a using argument
126 >>> using_manually_managed_mistake = transaction.commit_manually(using='default')(manually_managed_mistake)
127 >>> using_manually_managed_mistake()
128 Traceback (most recent call last):
130 TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK
134 # Regression for #11900: If a function wrapped by commit_on_success writes a
135 # transaction that can't be committed, that transaction should be rolled back.
136 # The bug is only visible using the psycopg2 backend, though
137 # the fix is generally a good idea.
138 pgsql_backends
= ('django.db.backends.postgresql_psycopg2', 'postgresql_psycopg2',)
139 if building_docs
or settings
.DATABASES
[DEFAULT_DB_ALIAS
]['ENGINE'] in pgsql_backends
:
140 __test__
['API_TESTS'] += """
141 >>> def execute_bad_sql():
142 ... cursor = connection.cursor()
143 ... cursor.execute("INSERT INTO transactions_reporter (first_name, last_name) VALUES ('Douglas', 'Adams');")
144 ... transaction.set_dirty()
146 >>> execute_bad_sql = transaction.commit_on_success(execute_bad_sql)
147 >>> execute_bad_sql()
148 Traceback (most recent call last):
150 IntegrityError: null value in column "email" violates not-null constraint
153 >>> transaction.rollback()