Hi,
I went through the frappe framework documents on Controller Hooks (Controllers) but I can’t seem to find an after_update or after_save hook. There is only an after_insert hook.
How do I execute a code after update of after save?
Does anyone have a sample code to achieve this?
Thank you very much
after_insert
is what you’re searching for. This is called after the document is inserted into the database.
on_update
also works.
1 Like
- Before the SQL UPDATE, the
validate()
function is called.
- After the SQL UPDATE, the
on_update()
function is called.
Unfortunately, the Controller functions have very inconsistent naming.
So, whenever I have doubts, I always examine the base Document
class. And read some of the comments that talk about the sequence of events.
../apps/frappe/frappe/model/document.py
2 Likes
Which method works same as after_save ?
You can use either after_insert
or on_update
. Both runs after saving.
It seems both on_update and on_change are called before data is saved to database
For example:
def on_change(self):
time.sleep(20)
When I update data in the doctype and click save
Expected: data in database will be updated before sleep 20 seconds
Actual: after I click save button, the system is slept in 20 seconds, but data in database is still old data
Your transaction is only committed to the database at the end of the request. Since you’re sleeping before the end of the request, your changes wouldn’t be committed until after the 20 seconds are complete.
If you need it to happen before that, you could try running the task in a separate thread using frappe.enqueue
or frappe.enqueue_doc
. If you like to live on the edge, you could call frappe.db.commit()
manually, but I wouldn’t recommend the last option. You probably don’t want the transaction to commit if something goes wrong after your manual commit.
Note, though, that you probably don’t need to do any of that unless you want to do something very specific. As far as your current thread is concerned, the data has been saved to the database already. Commit isn’t necessary for your thread to read the data pre-commit.
1 Like
after_insert controller works same.