Skip to content

Commit c9a02aa

Browse files
committed
add on_commit logic to mixin
1 parent 6d96843 commit c9a02aa

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

django_lifecycle/mixins.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,8 @@ def _run_hooked_methods(self, hook: str, **kwargs) -> List[str]:
200200
for callback_specs in method._hooked:
201201
if callback_specs["hook"] != hook:
202202
continue
203+
204+
on_commit = callback_specs.get("on_commit", False)
203205

204206
when_field = callback_specs.get("when")
205207
when_any_field = callback_specs.get("when_any")
@@ -225,10 +227,26 @@ def _run_hooked_methods(self, hook: str, **kwargs) -> List[str]:
225227
]
226228
):
227229
continue
230+
231+
# Save method name before potentially wrapping with `on_commit`
232+
method_name = method.__name__
233+
234+
# Apply `on_commit` after saving the method as `fired` to preserve
235+
# the non-anonymous name
236+
if on_commit:
237+
# Append `_on_commit` to the existing method name to allow for firing
238+
# the same hook within the atomic transaction and on_commit
239+
method_name = method_name + "_on_commit"
240+
241+
def _on_commit_func():
242+
method(self)
243+
244+
transaction.on_commit(_on_commit_func)
245+
else:
246+
method(self)
228247

229248
# Only call the method once per hook
230-
fired.append(method.__name__)
231-
method(self)
249+
fired.append(method_name)
232250
break
233251

234252
return fired

0 commit comments

Comments
 (0)