Lets say I have a model called BookModel with 4 fields : (title, author, price, publish_year).
And I have a handler in signals:
@receiver([post_save, post_delete], sender=BookModel)
def signal_handler(sender, instance, **kwargs):
…..
Question is how to distinguish a situation when specific model field has changed during save(). For example if price has changed I want to do stuff. Better explain in pseudo code...
@receiver([post_save, post_delete], sender=BookModel)
def signal_handler(sender, instance, **kwargs):
# pseudo code bellow
if field “price” has changed:
do stuff
else:
do nothing
According the docs if I use “update_fields” in save() - it is possible, but what if I dont use it???
Also is it possible to distinguish a situation when I received signal from post_save or from post_delete still using 1 handler?
@receiver([post_save, post_delete], sender=BookModel)
def signal_handler(sender, instance, **kwargs):
# pseudo code bellow
if signal is post_save:
if field “price” has changed:
do stuff
else:
do nothing
else:
do other stuff
Thanks
You can try django-model-utils's FieldTracker to track changes in model fields. It also use with post_save
signal.
Checking changes using signals
The field tracker methods may also be used in pre_save and post_save signal handlers to identify field changes on model save.