0
0
Djangoframework~10 mins

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

Choose your learning style9 modes available
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.