Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run some code when a Django model’s save method is called for the first time?

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?

like image 296
Paul D. Waite Avatar asked Jan 18 '12 20:01

Paul D. Waite


2 Answers

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)
like image 157
bwooceli Avatar answered Nov 18 '22 12:11

bwooceli


Ah yes: the post_save signal passes an argument called created, which is True if its instance was created by the call to save().

like image 22
Paul D. Waite Avatar answered Nov 18 '22 13:11

Paul D. Waite