How to only perform action once instance created?

Question:

My code:

def save(self, *args, **kwargs):
  <My_CODE>
  if <having_register>:
    <send_email_to_admin>

but this function will work when I run an update instance ( The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the "save" must be an SQL insert or update )
so if I just want to send an email to admin only once having a new registration? Any way to check the request method or prevent force_insert in this case?

Asked By: Kev

||

Answers:

You can check the value of the pk:

def save(self, *args, **kwargs):
  <My_CODE>
  if self.pk is None:
    <send_email_to_admin>

Otherwise you could send the email in the view after having called save.

Answered By: Alain Bianchini

Another way you can solve this is by using django signals, and use the post_save signal and check the created parameter. A good example for django signals could be this one here, it shows the setup needed for django signals to work.

from django.db.models.signals import post_save
from django.dispatch import receiver

from yourApp.models import yourModel

@receiver(post_save, sender=yourModel)
def new_instance_created(sender, instance, created, **kwargs):
    if created:
       <send_email_to_admin>
        
Answered By: Mathews Musukuma