Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: how can I tell if the post_save signal triggers on a new object?

People also ask

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.

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.

Are Django signals asynchronous?

To answer directly: No. It's sync.


Have a look at docs: https://docs.djangoproject.com/en/stable/ref/signals/#post-save

There is a created named argument which will be set to True if it's a new object.


As Docs stated and @seler pointed out, but with an example:

def keep_track_save(sender, instance, created, **kwargs):
    action = 'save' if created else 'update'
    save_duplicate((instance.id, instance.__class__.__name__, action))

post_save.connect(keep_track_save, sender=Group)

I just leave it here, maybe it'll be helpful for someone.

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


class Deal(models.Model):
    name = models.CharField(max_length=255)


@receiver(post_save, sender=Deal)
def print_only_after_deal_created(sender, instance, created, **kwargs):
    if created:
        print(f'New deal with pk: {instance.pk} was created.')