Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
ForeignKey for one-to-many
📖 Scenario: You are building a simple blog application where each blog post can have many comments. You want to connect comments to their blog posts using Django's ForeignKey to show this one-to-many relationship.
🎯 Goal: Create two Django models: Post and Comment. Use a ForeignKey in Comment to link each comment to a single post. This will let you store multiple comments for each post.
📋 What You'll Learn
Create a Post model with a title field
Create a Comment model with a text field
Add a ForeignKey in Comment to Post with on_delete=models.CASCADE
Use related_name='comments' in the ForeignKey for easy access from Post
Follow Django model syntax and conventions
💡 Why This Matters
🌍 Real World
Blogs, forums, and social media apps often use one-to-many relationships to connect posts with comments or replies.
💼 Career
Understanding ForeignKey relationships is essential for backend developers working with Django to build relational data models.
Progress0 / 4 steps
1
Create the Post model
Create a Django model called Post with a single field title that is a CharField with max length 100.
Django
Hint
Use models.CharField(max_length=100) for the title field inside the Post model.
2
Create the Comment model
Create a Django model called Comment with a single field text that is a TextField.
Django
Hint
Use models.TextField() for the text field inside the Comment model.
3
Add ForeignKey to Comment
Add a ForeignKey field called post to the Comment model. It should link to the Post model, use on_delete=models.CASCADE, and have related_name='comments'.
Django
Hint
Use models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') for the post field.
4
Add __str__ methods for readability
Add a __str__ method to both Post and Comment models. For Post, return the title. For Comment, return the first 20 characters of text.
Django
Hint
Define __str__ methods to return self.title for Post and self.text[:20] for Comment.
Practice
(1/5)
1. In Django, where should you place a ForeignKey field to represent a one-to-many relationship?
easy
A. In the model representing the 'many' side of the relationship
B. In the model representing the 'one' side of the relationship
C. In both models to link them together
D. You don't use ForeignKey for one-to-many relationships
Solution
Step 1: Understand the one-to-many relationship
One object on the 'one' side can relate to many objects on the 'many' side.
Step 2: Place ForeignKey on the 'many' side
The ForeignKey field goes in the model that represents the 'many' side to link back to the 'one' side.
Final Answer:
In the model representing the 'many' side of the relationship -> Option A
Quick Check:
ForeignKey on 'many' side = A [OK]
Hint: ForeignKey always goes on the 'many' side model [OK]
Common Mistakes:
Putting ForeignKey on the 'one' side model
Adding ForeignKey to both models
Thinking ForeignKey is not used for one-to-many
2. Which of the following is the correct syntax to define a ForeignKey in a Django model named Book that links to a model named Author?
easy
A. author = models.ForeignKey(Author, delete=models.CASCADE)
B. author = models.ForeignKey(Author, on_delete=models.CASCADE)
C. author = models.ForeignKey('Author')
D. author = models.ForeignKey(Author, on_delete='CASCADE')
Solution
Step 1: Check ForeignKey syntax
ForeignKey requires the related model and the on_delete argument to specify delete behavior.
Step 2: Validate correct usage
author = models.ForeignKey(Author, on_delete=models.CASCADE) correctly uses on_delete=models.CASCADE. Options A, B, and D have syntax errors or missing required arguments.
Final Answer:
author = models.ForeignKey(Author, on_delete=models.CASCADE) -> Option B
Quick Check:
Correct ForeignKey syntax = C [OK]
Hint: Always include on_delete=models.CASCADE with ForeignKey [OK]
Common Mistakes:
Omitting on_delete argument
Using wrong argument name like delete
Passing on_delete as string instead of constant
3. Given these models:
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
What will Book.objects.filter(author__name='Alice').count() return if there are 3 books by Alice and 2 by Bob?
medium
A. 0
B. 2
C. 5
D. 3
Solution
Step 1: Understand the filter query
The query filters books where the related author's name is 'Alice'.
Step 2: Count matching books
Since 3 books belong to Alice, the count will be 3.
Final Answer:
3 -> Option D
Quick Check:
Books by Alice = 3 [OK]
Hint: Filter on related model with double underscore __ [OK]
Common Mistakes:
Counting authors instead of books
Using single underscore instead of double
Confusing author name with book title
4. What is wrong with this Django model code?
class Comment(models.Model):
post = models.ForeignKey(Post)
text = models.TextField()
medium
A. TextField cannot be used for text
B. ForeignKey should be named post_id
C. Missing on_delete argument in ForeignKey
D. ForeignKey should be in Post model
Solution
Step 1: Check ForeignKey arguments
Since Django 2.0, on_delete is required for ForeignKey fields.
Step 2: Identify missing on_delete
The code lacks on_delete, causing an error.
Final Answer:
Missing on_delete argument in ForeignKey -> Option C
Quick Check:
ForeignKey requires on_delete argument [OK]
Hint: Always add on_delete to ForeignKey fields [OK]
Common Mistakes:
Forgetting on_delete causes errors
Renaming ForeignKey field incorrectly
Thinking TextField is invalid for text
5. You have these models:
class Category(models.Model):
name = models.CharField(max_length=50)
class Product(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
If a Category is deleted, what happens to its related Products?
hard
A. Products remain but their category field is set to NULL
B. Products are deleted automatically
C. Deletion of Category is blocked if Products exist
D. Products keep the deleted category reference
Solution
Step 1: Understand on_delete=models.SET_NULL
This option sets the ForeignKey field to NULL when the related object is deleted.
Step 2: Apply to Product-Category relation
When a Category is deleted, related Products keep their records but their category field becomes NULL.
Final Answer:
Products remain but their category field is set to NULL -> Option A
Quick Check:
on_delete=SET_NULL means keep products, nullify category [OK]
Hint: SET_NULL keeps related objects, clears ForeignKey [OK]