I could have sworn I’d read a question about this before, but I can’t find it, so:
In Django, how can I run some code when a new model instance is saved to the database?
I know I can write a custom MyModel().save()
method to run some code whenever a model instance is saved. But how can I run code only when a model instance is saved for the first time?
Django documentation was hard for me to grok at first, here's a more explicit example
from django.db.models.signals import post_save
from yourapp.models import YourModel
def model_created(sender, **kwargs):
the_instance = kwargs['instance']
if kwargs['created']:
do_some_stuff(the_instance)
post_save.connect(model_created, sender=YourModel)
Ah yes: the post_save
signal passes an argument called created
, which is True
if its instance was created by the call to save()
.
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