Bird
Raised Fist0
Djangoframework~20 mins

ForeignKey for one-to-many in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
ForeignKey Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What does this Django model relationship produce?
Given these Django models, what will be the output of print(book.author.name) if book is an instance of Book linked to an Author named 'Alice'?
Django
from django.db import 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)

# Assume book is a Book instance linked to Author named 'Alice'
print(book.author.name)
ARaises AttributeError because 'author' is not accessible
B"Alice"
C"book.author"
DNone
Attempts:
2 left
💡 Hint
Remember that ForeignKey creates a link to a single related object.
state_output
intermediate
2:00remaining
How many books are related to this author?
Given these models and an Author instance author with 3 related Book instances, what is the output of print(author.book_set.count())?
Django
from django.db import 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)

# Assume author is an Author instance with 3 books linked
print(author.book_set.count())
ARaises AttributeError because 'book_set' does not exist
B0
C3
DRaises TypeError
Attempts:
2 left
💡 Hint
Django automatically creates a reverse relation named modelname_set.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a ForeignKey for one-to-many in Django?
Select the correct Django model field definition to create a one-to-many relationship from Book to Author.
Django
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    # ForeignKey field here
Aauthor = models.ForeignKey(Author, on_delete=models.CASCADE)
Bauthor = models.CharField(max_length=100)
Cauthor = models.ManyToManyField(Author)
Dauthor = models.OneToOneField(Author, on_delete=models.CASCADE)
Attempts:
2 left
💡 Hint
One-to-many uses ForeignKey, not OneToOneField or ManyToManyField.
🔧 Debug
advanced
2:00remaining
Why does this code raise an error?
Given these models, why does accessing book.author_set.all() raise an error?
Django
from django.db import 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)

book = Book.objects.first()
print(book.author_set.all())
A'Author' object has no attribute 'author_set' because of typo
BNone, code runs without error
CSyntaxError due to missing parentheses in ForeignKey
D'Book' object has no attribute 'author_set' because reverse relation is on Author, not Book
Attempts:
2 left
💡 Hint
Reverse relations are accessed from the model on the 'one' side, not the 'many' side.
🧠 Conceptual
expert
3:00remaining
What happens when you delete an Author instance linked to Books with on_delete=models.CASCADE?
Consider these models with author = models.ForeignKey(Author, on_delete=models.CASCADE). What is the effect on related Book instances when an Author is deleted?
Django
from django.db import 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)
AAll Book instances linked to the deleted Author are also deleted
BBook instances remain but their author field is set to NULL
CDeletion of Author is blocked if any Book is linked
DBook instances remain unchanged with author field still pointing to deleted Author
Attempts:
2 left
💡 Hint
on_delete=models.CASCADE means related objects are deleted too.

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

  1. Step 1: Understand the one-to-many relationship

    One object on the 'one' side can relate to many objects on the 'many' side.
  2. 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.
  3. Final Answer:

    In the model representing the 'many' side of the relationship -> Option A
  4. 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

  1. Step 1: Check ForeignKey syntax

    ForeignKey requires the related model and the on_delete argument to specify delete behavior.
  2. 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.
  3. Final Answer:

    author = models.ForeignKey(Author, on_delete=models.CASCADE) -> Option B
  4. 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

  1. Step 1: Understand the filter query

    The query filters books where the related author's name is 'Alice'.
  2. Step 2: Count matching books

    Since 3 books belong to Alice, the count will be 3.
  3. Final Answer:

    3 -> Option D
  4. 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

  1. Step 1: Check ForeignKey arguments

    Since Django 2.0, on_delete is required for ForeignKey fields.
  2. Step 2: Identify missing on_delete

    The code lacks on_delete, causing an error.
  3. Final Answer:

    Missing on_delete argument in ForeignKey -> Option C
  4. 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

  1. Step 1: Understand on_delete=models.SET_NULL

    This option sets the ForeignKey field to NULL when the related object is deleted.
  2. Step 2: Apply to Product-Category relation

    When a Category is deleted, related Products keep their records but their category field becomes NULL.
  3. Final Answer:

    Products remain but their category field is set to NULL -> Option A
  4. Quick Check:

    on_delete=SET_NULL means keep products, nullify category [OK]
Hint: SET_NULL keeps related objects, clears ForeignKey [OK]
Common Mistakes:
  • Assuming related objects are deleted
  • Thinking deletion is blocked
  • Believing ForeignKey keeps deleted references