0
0
Djangoframework~30 mins

Model relationships preview in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Model relationships preview
📖 Scenario: You are building a simple Django app to manage books and their authors. Each book has one author, and each author can have multiple books.
🎯 Goal: Create two Django models, Author and Book, with a one-to-many relationship. Then, write a query to get all books by a specific author.
📋 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
Create a variable author_name with the value 'Jane Austen'
Write a Django ORM query to get all books by the author with name author_name
💡 Why This Matters
🌍 Real World
Managing related data like authors and books is common in library or bookstore apps.
💼 Career
Understanding model relationships and queries is essential for backend Django development.
Progress0 / 4 steps
1
Create the Author model
Create a Django model called Author with a single field name as a CharField with max length 100.
Django
Need a hint?

Use models.CharField(max_length=100) for the name field.

2
Create the Book model with a foreign key
Create a Django model called Book with a title field as CharField max length 200, and a foreign key field called author linking to the Author model with on_delete=models.CASCADE.
Django
Need a hint?

Use models.ForeignKey(Author, on_delete=models.CASCADE) for the author field.

3
Create the author_name variable
Create a variable called author_name and set it to the string 'Jane Austen'.
Django
Need a hint?

Set author_name exactly to 'Jane Austen'.

4
Query books by author name
Write a Django ORM query to get all Book objects where the related Author's name matches the variable author_name. Assign the result to a variable called books_by_author.
Django
Need a hint?

Use Book.objects.filter(author__name=author_name) to get books by author name.