0
0
DjangoConceptBeginner · 3 min read

What is pre_delete Signal in Django: Explanation and Example

The pre_delete signal in Django is sent just before a model instance is deleted from the database. It allows you to run custom code or cleanup tasks right before the deletion happens.
⚙️

How It Works

Imagine you have a to-do list app and you want to do something special right before a task is removed, like saving a backup or logging the deletion. The pre_delete signal is like a notification that Django sends just before it deletes an item from the database.

This signal lets you attach a function that will run automatically before the deletion happens. It’s like a last chance to prepare or clean up related data. For example, if your task has attached files, you might want to delete those files from storage before the task disappears.

Under the hood, Django sends this signal every time you call the delete() method on a model instance or when a queryset deletes multiple objects. Your connected function receives the instance being deleted and can act accordingly.

💻

Example

This example shows how to use the pre_delete signal to print a message before deleting a Book object.

python
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch import receiver

class Book(models.Model):
    title = models.CharField(max_length=100)

@receiver(pre_delete, sender=Book)
def before_book_delete(sender, instance, **kwargs):
    print(f"About to delete book: {instance.title}")
Output
About to delete book: The Great Gatsby
🎯

When to Use

Use the pre_delete signal when you need to perform actions right before an object is removed. Common uses include:

  • Cleaning up related files or data that won’t be deleted automatically.
  • Logging or auditing deletions for tracking changes.
  • Canceling deletion by raising an exception if certain conditions are not met.

For example, if you have user-uploaded images linked to a model, you can delete those images from the file system before the model instance is deleted to avoid orphaned files.

Key Points

  • pre_delete runs before the database deletes the object.
  • You can connect multiple functions to this signal for different cleanup tasks.
  • It works for both single instance and bulk deletions.
  • Raising an exception in the signal handler stops the deletion.
  • Always disconnect signals if not needed to avoid unexpected behavior.

Key Takeaways

The pre_delete signal lets you run code just before a model instance is deleted.
Use it to clean up related data or log deletions.
You connect a function to pre_delete using the @receiver decorator.
Raising an exception in the signal handler can stop the deletion process.
pre_delete works for both single and bulk deletions.