0
0
Djangoframework~30 mins

Why relationships model real-world data in Django - See It in Action

Choose your learning style9 modes available
Why relationships model real-world data
📖 Scenario: You are building a simple Django app to manage a library. Books have authors, and each author can write many books. This shows how relationships in Django models represent real-world connections.
🎯 Goal: Create Django models that show a one-to-many relationship between authors and books. This will help you understand how Django uses relationships to model real-world data.
📋 What You'll Learn
Create an Author model with a name field
Create a Book model with a title field
Add a foreign key in Book to link to Author
Use Django's models.ForeignKey with on_delete=models.CASCADE
💡 Why This Matters
🌍 Real World
Modeling relationships like authors and books helps organize data clearly in apps like libraries, bookstores, or publishing platforms.
💼 Career
Understanding Django model relationships is essential for backend developers building database-driven web applications.
Progress0 / 4 steps
1
Create the Author model
Create a Django model called Author with a single field name that is a models.CharField with max_length=100.
Django
Need a hint?

Use models.CharField for text fields and set max_length to 100.

2
Create the Book model
Create a Django model called Book with a single field title that is a models.CharField with max_length=200.
Django
Need a hint?

Use models.CharField for the book title with a max length of 200 characters.

3
Add relationship from Book to Author
In the Book model, add a field called author that is a models.ForeignKey to the Author model with on_delete=models.CASCADE.
Django
Need a hint?

Use models.ForeignKey to link Book to Author. The on_delete=models.CASCADE means if an author is deleted, their books are deleted too.

4
Complete the models with string representation
Add a __str__ method to both Author and Book models that return the name and title fields respectively.
Django
Need a hint?

The __str__ method helps show friendly names in Django admin and shell.