0
0
Djangoframework~30 mins

Relationship query patterns in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Relationship Query Patterns in Django
📖 Scenario: You are building a simple library system. There are Authors and Books. Each book is written by one author. You want to practice how to query related data using Django's ORM.
🎯 Goal: Create Django models for Author and Book with a relationship. Then write queries to find all books by a specific author and all authors who have written books.
📋 What You'll Learn
Create a Django model Author with a name field
Create a Django model Book with a title field and a foreign key to Author
Write a query to get all books by the author named 'Jane Austen'
Write a query to get all authors who have written at least one book
💡 Why This Matters
🌍 Real World
Managing related data is common in web apps like libraries, blogs, or stores. Knowing how to query related models helps you build powerful features.
💼 Career
Django developers often work with related models. Mastering relationship queries is essential for backend development and data handling.
Progress0 / 4 steps
1
Create Author and Book models
Create a Django model called Author with a name field as models.CharField(max_length=100). Also create a model called Book with a title field as models.CharField(max_length=200) and a foreign key called author to Author using models.ForeignKey(Author, on_delete=models.CASCADE).
Django
Need a hint?

Remember to import models from django.db. Use models.CharField for text fields and models.ForeignKey for relationships.

2
Set author name to query
Create a variable called author_name and set it to the string 'Jane Austen'. This will be used to find books by this author.
Django
Need a hint?

Just create a variable author_name and assign the exact string 'Jane Austen'.

3
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 double underscores author__name to filter books by the author's name.

4
Query authors with books
Write a Django ORM query to get all Author objects who have written at least one book. Assign the result to a variable called authors_with_books. Use distinct() to avoid duplicates.
Django
Need a hint?

Use book__isnull=False to find authors with books and add distinct() to avoid duplicates.