Django signals check if new instance
In Django, signals are a way to notify other parts of your application that something has happened, such as an object being created, updated, or deleted. When using signals, you can check if a new instance is being created by checking the created
attribute of the post_save
signal.
Here's an example:
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=MyModel)
def my_signal_handler(sender, instance, created, **kwargs):
if created:
# This is a new instance being created
print("New instance created!")
else:
# This is an existing instance being updated
print("Instance updated!")
In this example, the my_signal_handler
function is a receiver for the post_save
signal sent by the MyModel
model. The created
attribute is a boolean that indicates whether the instance being saved is a new instance (i.e., created=True
) or an existing instance being updated (i.e., created=False
).
You can also use the instance.pk
attribute to check if the instance has a primary key (i.e., it's a new instance) or not (i.e., it's an existing instance being updated). If the instance has a primary key, it's an existing instance being updated. If the instance doesn't have a primary key, it's a new instance being created.
Here's an example:
@receiver(post_save, sender=MyModel)
def my_signal_handler(sender, instance, **kwargs):
if instance.pk is None:
# This is a new instance being created
print("New instance created!")
else:
# This is an existing instance being updated
print("Instance updated!")
Note that the created
attribute is only available for the post_save
signal, not for other signals like post_delete
or post_init
. If you need to check if an instance is new or not for other signals, you'll need to use the instance.pk
attribute or another mechanism to determine whether the instance is new or not.