Junior — Middle
Can you explain the purpose and operation of the post_save signal in Django?
sobes.tech AI
Answer from AI
The post_save signal in Django is one of the built-in signals that is sent after an instance of a model is saved to the database.
The purpose of post_save is to allow the execution of additional code immediately after a model object has been created or updated. This is useful for automating actions related to data changes, such as:
- Creating related objects
- Sending notifications
- Logging changes
Example of usage:
from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import MyModel
@receiver(post_save, sender=MyModel)
def mymodel_post_save(sender, instance, created, **kwargs):
if created:
print(f'New object created: {instance}')
else:
print(f'Object updated: {instance}')
Here, created is a boolean value indicating whether the object was created for the first time (True) or updated (False).