Bird
Raised Fist0
Djangoframework~10 mins

ForeignKey for one-to-many in Django - Step-by-Step Execution

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
Concept Flow - ForeignKey for one-to-many
Define Parent Model
Define Child Model with ForeignKey to Parent
Create Parent Instance
Create Child Instances linked to Parent
Access Child Instances from Parent
Use QuerySet to get all children
Display or use related children
This flow shows how a parent model is linked to many child models using ForeignKey, then how to create and access these linked records.
Execution Sample
Django
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)
Defines Author as parent and Book as child with ForeignKey linking each book to one author.
Execution Table
StepActionEvaluationResult
1Create Author instanceAuthor(name='Alice')Author object saved with id=1
2Create Book instance linked to AuthorBook(title='Book A', author=Author(id=1))Book object saved with id=1 linked to Author id=1
3Create another Book linked to same AuthorBook(title='Book B', author=Author(id=1))Book object saved with id=2 linked to Author id=1
4Access books from Authorauthor.book_set.all()QuerySet with Book id=1 and id=2
5Iterate over booksfor book in author.book_set.all():Outputs titles 'Book A' and 'Book B'
6ExitNo more booksIteration ends
💡 All books linked to the author have been accessed and iteration ends
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
authorNoneAuthor(id=1, name='Alice')Author(id=1, name='Alice')Author(id=1, name='Alice')Author(id=1, name='Alice')Author(id=1, name='Alice')
book1NoneNoneBook(id=1, title='Book A', author=1)Book(id=1, title='Book A', author=1)Book(id=1, title='Book A', author=1)Book(id=1, title='Book A', author=1)
book2NoneNoneNoneBook(id=2, title='Book B', author=1)Book(id=2, title='Book B', author=1)Book(id=2, title='Book B', author=1)
books_querysetNoneNoneNoneNoneQuerySet([Book(id=1), Book(id=2)])QuerySet([Book(id=1), Book(id=2)])
Key Moments - 2 Insights
Why do we use author.book_set.all() to get books instead of a direct attribute?
Because Django automatically creates a reverse relation named book_set for the ForeignKey. This lets us access all Book objects linked to that Author, as shown in step 4 of the execution_table.
What happens if we delete the Author instance?
Since on_delete=models.CASCADE is set, deleting the Author will also delete all linked Book instances. This is important to keep data consistent, as implied by the ForeignKey setup.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what does author.book_set.all() return?
AA single Book instance
BAn empty list
CA QuerySet containing all Book instances linked to the author
DThe Author instance itself
💡 Hint
Check the 'Result' column at step 4 in execution_table
At which step are multiple Book instances linked to the same Author?
AStep 3
BStep 2
CStep 1
DStep 5
💡 Hint
Look at when book2 is created linked to author in variable_tracker
If we change on_delete=models.SET_NULL instead of CASCADE, what changes in behavior?
ABooks get deleted when Author is deleted
BBooks remain but their author field becomes null
CAuthor cannot be deleted
DNothing changes
💡 Hint
Consider the meaning of on_delete options in ForeignKey
Concept Snapshot
ForeignKey links many child records to one parent.
Define ForeignKey in child model pointing to parent.
Use parent.child_set.all() to get all children.
on_delete controls what happens if parent is deleted.
Commonly used for one-to-many relationships.
Full Transcript
This visual execution shows how Django's ForeignKey creates a one-to-many link between models. We start by defining a parent model Author and a child model Book with a ForeignKey to Author. When we create an Author instance and multiple Book instances linked to it, Django stores these relations in the database. Accessing author.book_set.all() returns all books linked to that author. The on_delete parameter controls behavior when the parent is deleted, with CASCADE deleting all linked children. This trace helps beginners see how data is connected and accessed step-by-step.

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