An elegant and simple way to fire a signal after a Save is complete (completely complete :) )

148 views
Skip to first unread message

Spiros Mouzakitis

unread,
Oct 14, 2014, 4:05:36 PM10/14/14
to django...@googlegroups.com
Hi all,

I have a model (model Employee) and i want to each time that it is created / saved to run a specific code block.
My specific code requires that the model is already saved in the database (i call an external API)
I can't use post_save signal , because the transaction is still pending (the database has not been updated).

What can i do? What is the most elegant way to create a (custom?) signal for after the save is complete? Can someone give an example?

many thanks,
Spiros

Carl Meyer

unread,
Oct 14, 2014, 5:06:08 PM10/14/14
to django...@googlegroups.com
Hi Spiros,
I don't know of a good _simple_ way to do this, but I think there are
some pieces you can put together to make a working solution.
Django-transaction-hooks [1] will let you register callback functions to
be run after the current transaction is committed. So you should be able
to write a post_save signal handler that registers a post-commit
callback for the just-saved model.

Carl


[1] http://django-transaction-hooks.readthedocs.org/en/latest/

Spiros Mouzakitis

unread,
Oct 14, 2014, 7:58:40 PM10/14/14
to django...@googlegroups.com
Thanks Carls,

What i finally did was to create a post_save signal as usual, and then in my receiver function i execute the "specific code block" in a thread (as mentioned here: http://stackoverflow.com/questions/11899088/is-django-post-save-signal-asynchronous)
In the thread i also put a time sleep. By the time the thread is resumed from the time.sleep function, the database has been updated and unlocked
It works, but definitely not elegant :)

Carl Meyer

unread,
Oct 14, 2014, 8:40:21 PM10/14/14
to django...@googlegroups.com
On 10/14/2014 01:58 PM, Spiros Mouzakitis wrote:
> What i finally did was to create a post_save signal as usual, and then
> in my receiver function i execute the "specific code block" in a thread
> (as mentioned
> here: http://stackoverflow.com/questions/11899088/is-django-post-save-signal-asynchronous)
> In the thread i also put a time sleep. By the time the thread is resumed
> from the time.sleep function, the database has been updated and unlocked
> It works, but definitely not elegant :)

I think using django-transaction-hooks would be both more elegant and
more reliable, and not any more complex than that.

Carl

Spiros Mouzakitis

unread,
Oct 15, 2014, 10:43:19 AM10/15/14
to django...@googlegroups.com
Thanks for the suggestion, i will also try django-transaction-hooks.
Reply all
Reply to author
Forward
0 new messages