0
0
Djangoframework~5 mins

pre_delete and post_delete signals in Django - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the pre_delete signal in Django?
The pre_delete signal is sent just before a model instance is deleted. It allows you to run custom code or cleanup tasks before the actual deletion happens.
Click to reveal answer
beginner
When is the post_delete signal triggered in Django?
The post_delete signal is triggered immediately after a model instance has been deleted from the database. It is useful for actions that should happen after deletion, like clearing caches or logging.
Click to reveal answer
intermediate
How do you connect a function to the pre_delete signal for a model?
You use the @receiver(pre_delete, sender=YourModel) decorator above your function or call pre_delete.connect(your_function, sender=YourModel). This tells Django to run your function before deleting instances of that model.
Click to reveal answer
intermediate
Can you stop the deletion of an object inside a pre_delete signal handler?
No, the pre_delete signal does not support stopping the deletion. It is only for running code before deletion. To prevent deletion, you should override the model's delete() method or use database constraints.
Click to reveal answer
beginner
Give an example use case for the post_delete signal.
A common use case is deleting related files from the file system after a model instance with a file field is deleted. The post_delete signal lets you remove those files safely after the database record is gone.
Click to reveal answer
Which signal runs before a Django model instance is deleted?
Apost_delete
Bpre_delete
Cpre_save
Dpost_save
What can you do inside a post_delete signal handler?
ARun code after the instance is deleted
BModify the instance before deletion
CPrevent the deletion
DCancel the deletion process
How do you connect a function to a Django signal?
ABy calling the signal directly in templates
BBy overriding the model's save() method
CUsing @receiver decorator or connect() method
DBy importing the signal in views.py
Can pre_delete signal stop the deletion of an object?
ANo, it only runs before deletion
BYes, by raising an exception
CYes, by returning False
DYes, by calling cancel()
Which of these is a good use for post_delete?
APreventing deletion of an object
BValidating data before saving
CModifying data before saving
DDeleting related files after record deletion
Explain the difference between pre_delete and post_delete signals in Django.
Think about when each signal is triggered relative to the deletion event.
You got /4 concepts.
    Describe how to connect a function to the pre_delete signal for a Django model and what you might use it for.
    Focus on the connection method and practical uses.
    You got /3 concepts.