I am using Django's pre_save signal to implement auto_now_add. There is a lot of discussion on the internet on why you should or shouldn't implement it yourself. I do not appreciate comments on this. Neither on whether I should be rewriting the save function (I have a lot of models that use auto_now_add so using signals makes sense).
My question is:
I would like to check if the instance is created or updated. According to some sources on the internet this can be done by testing if kwargs['created']
is True. However 'created'
does not appear in my kwargs
even though the instance is newly created. I was just wondering if it has ever existed or that it has disappeared magically. I know I could also test if kwargs['instance'].id
is set (this in fact works for me), but I'd like to know if kwargs['created'] still exists.
There are two ways to send signals in Django. To send a signal, call either Signal. send() (all built-in signals use this) or Signal. send_robust() .
The Django Signals is a strategy to allow decoupled applications to get notified when certain events occur. Let's say you want to invalidate a cached page everytime a given model instance is updated, but there are several places in your code base that this model can be updated.
Django Signals - post_delete()To notify another part of the application after the delete event of an object happens, you can use the post_delete signal.
pre_save. This is sent at the beginning of a model's save() method. Arguments sent with this signal: sender.
Primary key attribute usually assigned by the database when the instance saved first time. So you can use something like if instance.pk is None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With