File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -21,6 +21,24 @@ def insert_movie_transaction():
21
21
)
22
22
# end-transaction-manager
23
23
24
+ # start-callback
25
+ def get_horror_comedies ():
26
+ movies = Movie .objects .filter (genres = ["Horror" , "Comedy" ])
27
+ for m in movies :
28
+ print (f"Title: { m .title } , runtime: { m .runtime } " )
29
+
30
+ def insert_movie_with_callback ():
31
+ with transaction .atomic ():
32
+ Movie .objects .create (
33
+ title = "The Substance" ,
34
+ runtime = 140 ,
35
+ genres = ["Horror" , "Comedy" ]
36
+ )
37
+
38
+ # Registers the callback to run only after the transaction commits
39
+ transaction .on_commit (get_horror_comedies )
40
+ # end-callback
41
+
24
42
# start-handle-errors
25
43
movie = Movie .objects .get (
26
44
title = "Jurassic Park" ,
Original file line number Diff line number Diff line change @@ -102,6 +102,24 @@ preceding example but uses a context manager to start a transaction:
102
102
:language: python
103
103
:copyable:
104
104
105
+ Run Callbacks After a Transaction
106
+ ---------------------------------
107
+
108
+ If you want to run certain operations only if a transaction successfully
109
+ completes, you can us the ``on_commit()`` method. This method allows you to
110
+ register callbacks that run after a transaction is committed to the
111
+ database. Pass a function, or any callable object, as an argument to
112
+ ``on_commit()``.
113
+
114
+ The following example queries for movies that have a genre value of
115
+ ``["Horror", "Comedy"]`` only after a related database transaction completes:
116
+
117
+ .. literalinclude:: /includes/interact-data/transactions.py
118
+ :start-after: start-callback
119
+ :end-before: end-callback
120
+ :language: python
121
+ :copyable:
122
+
105
123
Handle Transaction Errors
106
124
-------------------------
107
125
You can’t perform that action at this time.
0 commit comments