0
0
Djangoframework~30 mins

On_delete options (CASCADE, PROTECT, SET_NULL) in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Using on_delete Options in Django Models
📖 Scenario: You are building a simple Django app to manage books and their authors. Each book is linked to one author.When an author is deleted, you want to control what happens to their books using different on_delete options.
🎯 Goal: Create Django models for Author and Book with a foreign key from Book to Author. Use the on_delete options CASCADE, PROTECT, and SET_NULL in different steps to see how they affect deleting authors.
📋 What You'll Learn
Create an Author model with a name field
Create a Book model with a title field and a foreign key to Author
Use on_delete=models.CASCADE in Step 3
Use on_delete=models.PROTECT in Step 3
Use on_delete=models.SET_NULL with null=True in Step 3
💡 Why This Matters
🌍 Real World
Managing related data in web apps is common. Knowing how to handle deletions safely prevents data loss or errors.
💼 Career
Django developers often design database models and must choose appropriate on_delete behaviors to maintain data integrity.
Progress0 / 4 steps
1
Create the Author model
Create a Django model called Author with a single field name that is a CharField with max length 100.
Django
Need a hint?

Use models.CharField(max_length=100) for the name field inside the Author model class.

2
Create the Book model with a foreign key to Author
Create a Django model called Book with a title field as a CharField with max length 200, and a foreign key field called author that links to the Author model. Do not add on_delete yet.
Django
Need a hint?

Use models.ForeignKey(Author, on_delete=models.CASCADE) for the author field. We will change on_delete in the next step.

3
Change on_delete to CASCADE, PROTECT, and SET_NULL
Modify the author foreign key in the Book model to use on_delete=models.CASCADE. Then, create two more versions of the Book model called BookProtect and BookSetNull where the author foreign key uses on_delete=models.PROTECT and on_delete=models.SET_NULL respectively. For BookSetNull, add null=True to the foreign key field.
Django
Need a hint?

Use on_delete=models.CASCADE for Book, on_delete=models.PROTECT for BookProtect, and on_delete=models.SET_NULL, null=True for BookSetNull.

4
Add __str__ methods for better display
Add a __str__ method to each model (Author, Book, BookProtect, and BookSetNull) that returns the name for Author and the title for the book models.
Django
Need a hint?

Define __str__ methods that return self.name for Author and self.title for the book models.