Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django pre_save signal: check if instance is created not updated, does kwargs['created'] (still) exist?

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.

like image 912
Heyl1 Avatar asked Aug 31 '10 09:08

Heyl1


People also ask

How do you call a signal in Django?

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() .

What is created in Django signals?

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.

What is the use of the Post_delete signal in Django?

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.

Where is Pre_save signal in Django?

pre_save. This is sent at the beginning of a model's save() method. Arguments sent with this signal: sender.


1 Answers

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

like image 144
Radagast Avatar answered Sep 30 '22 19:09

Radagast