What is post_save signal in Django: Explanation and Example
post_save signal is triggered automatically right after a model's save() method completes. It allows you to run custom code whenever a model instance is created or updated.How It Works
The post_save signal in Django acts like a notification system that tells your app when a model object has just been saved to the database. Imagine you have a friend who calls you every time they finish a task; similarly, Django 'calls' your signal handler after saving.
This signal sends information about the saved object, whether it was newly created or just updated, and other details. You can connect your own function to this signal to perform extra actions, like sending an email, updating related data, or logging changes.
Example
This example shows how to use the post_save signal to print a message whenever a Book model is saved.
from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) @receiver(post_save, sender=Book) def book_saved(sender, instance, created, **kwargs): if created: print(f"A new book titled '{instance.title}' was added.") else: print(f"The book titled '{instance.title}' was updated.")
When to Use
Use the post_save signal when you want to automatically trigger actions right after saving a model. For example:
- Send a welcome email when a new user registers.
- Update a summary or cache after data changes.
- Log changes for audit purposes.
- Create related objects automatically after saving.
This helps keep your code organized by separating side effects from the main save logic.
Key Points
- post_save runs after a model instance is saved.
- You can detect if the instance was created or updated.
- It helps automate tasks triggered by data changes.
- Use
@receiverdecorator to connect functions cleanly.