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():
2121 )
2222# end-transaction-manager
2323
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+
2442# start-handle-errors
2543movie = Movie .objects .get (
2644 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:
102102 :language: python
103103 :copyable:
104104
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+
105123Handle Transaction Errors
106124-------------------------
107125
You can’t perform that action at this time.
0 commit comments