0
0
Djangoframework~10 mins

Related name for reverse access in Django - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Related name for reverse access
Define ForeignKey with related_name
Create model instances
Access related objects via related_name
Use reverse lookup in queries or templates
Get related objects list or queryset
This flow shows how defining related_name on a ForeignKey allows reverse access from the related model to the original model's instances.
Execution Sample
Django
class Book(models.Model):
    author = models.ForeignKey('Author', related_name='books', on_delete=models.CASCADE)

# Access reverse: author.books.all()
Defines a ForeignKey with related_name 'books' to access all books of an author from the author instance.
Execution Table
StepActionCode/ExpressionResult/Value
1Define ForeignKey with related_nameauthor = models.ForeignKey('Author', related_name='books', on_delete=models.CASCADE)Sets reverse accessor name to 'books'
2Create Author instanceauthor = Author.objects.create(name='Alice')Author object with id=1
3Create Book instance linked to authorbook = Book.objects.create(author=author, title='Django Basics')Book object linked to author id=1
4Access books from author using related_nameauthor.books.all()QuerySet containing the book 'Django Basics'
5Add another Book for same authorBook.objects.create(author=author, title='Advanced Django')Second book linked to author id=1
6Access books againauthor.books.all()QuerySet with two books: 'Django Basics', 'Advanced Django'
7Access books from unrelated authorother_author.books.all()Empty QuerySet if no books linked
8ExitNo more stepsReverse access works via related_name 'books'
💡 Execution stops after confirming reverse access via related_name returns correct related objects.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5Final
authorNoneAuthor(id=1, name='Alice')Author(id=1, name='Alice')Author(id=1, name='Alice')Author(id=1, name='Alice')
bookNoneNoneBook(id=1, title='Django Basics', author=1)Book(id=1, title='Django Basics', author=1)Book(id=1, title='Django Basics', author=1)
author.books.all()N/AEmpty QuerySetQuerySet with 1 bookQuerySet with 2 booksQuerySet with 2 books
Key Moments - 3 Insights
Why do we use related_name instead of the default reverse accessor?
The default reverse accessor is modelname_set (e.g., book_set). Using related_name lets us choose a clearer, friendlier name like 'books' for author.books.all(), as shown in steps 1 and 4.
What happens if we don't set related_name and try to access reverse relation?
Django uses the default name modelname_set (e.g., author.book_set.all()). This can be less readable and may conflict if multiple ForeignKeys exist. See step 4 for how related_name changes this.
Can related_name be the same on multiple ForeignKeys to the same model?
No, related_name must be unique per model to avoid reverse accessor conflicts. Otherwise, Django raises an error during model validation.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what does author.books.all() return after step 3?
AA QuerySet with one book titled 'Django Basics'
BAn empty QuerySet
CA QuerySet with two books
DAn error because related_name is missing
💡 Hint
Check the 'Result/Value' column at step 4 in the execution_table.
At which step does author.books.all() first return two books?
AStep 3
BStep 5
CStep 6
DStep 7
💡 Hint
Look at the 'Result/Value' for author.books.all() in steps 5 and 6.
If we remove related_name from the ForeignKey, how would the reverse access change?
AReverse access would not be possible
BWe would use author.book_set.all() instead of author.books.all()
Cauthor.books.all() would still work
DDjango would raise an error at runtime
💡 Hint
Recall the explanation in key_moments about default reverse accessor names.
Concept Snapshot
In Django models, related_name sets the name for reverse access from the related model.
Use related_name='books' on ForeignKey to Author to access all books via author.books.all().
Without related_name, Django uses default modelname_set (e.g., book_set).
This improves code readability and avoids conflicts.
Reverse access returns a QuerySet of related objects.
Full Transcript
This visual execution traces how Django's related_name on a ForeignKey defines the reverse accessor name. First, the ForeignKey is defined with related_name='books'. Then, an Author instance is created, followed by creating Book instances linked to that author. Accessing author.books.all() returns a QuerySet of all books linked to that author. Adding more books updates this QuerySet. The variable tracker shows author and book instances and how author.books.all() changes from empty to containing one and then two books. Key moments clarify why related_name is used, what happens if omitted, and uniqueness requirements. The quiz tests understanding of when and how reverse access works and the effect of removing related_name. The snapshot summarizes the concept for quick recall.