Paul D. Waite
Paul D. Waite

Reputation: 98786

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?

Upvotes: 5

Views: 3198

Answers (2)

bwooceli
bwooceli

Reputation: 371

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)

Upvotes: 4

Paul D. Waite
Paul D. Waite

Reputation: 98786

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

Upvotes: 4

Related Questions