Related name lets you easily find all items linked to another item in a database. It helps you go backward from one object to many connected objects.
Related name for reverse access in Django
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Django
class ModelA(models.Model): # fields class ModelB(models.Model): model_a = models.ForeignKey(ModelA, related_name='related_name_here', on_delete=models.CASCADE) # other fields
The related_name is a string you choose to name the reverse link.
Use related_name inside the ForeignKey or OneToOneField to set the reverse accessor.
Examples
author.books.all().Django
class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE) title = models.CharField(max_length=200)
customer.orders.all() to get all orders for a customer.Django
class Customer(models.Model): name = models.CharField(max_length=100) class Order(models.Model): customer = models.ForeignKey(Customer, related_name='orders', on_delete=models.CASCADE) order_date = models.DateField()
project.tasks.all().Django
class Project(models.Model): title = models.CharField(max_length=100) class Task(models.Model): project = models.ForeignKey(Project, related_name='tasks', on_delete=models.CASCADE) description = models.TextField()
Sample Program
This example shows how to set a related name 'books' to access all books of an author easily.
Django
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE) title = models.CharField(max_length=200) # Usage example (not part of models): # author = Author.objects.create(name='Alice') # Book.objects.create(author=author, title='Book One') # Book.objects.create(author=author, title='Book Two') # print([book.title for book in author.books.all()])
Important Notes
If you don't set related_name, Django uses modelname_set by default (e.g., author.book_set.all()).
Choose clear and meaningful related names to keep your code readable.
Summary
related_name sets the name to access related objects backward.
It helps you get all linked items from the other side easily.
Always use it to make your code clearer and avoid default names.
Practice
1. What does the
related_name attribute do in a Django model's ForeignKey field?easy
Solution
Step 1: Understand the purpose of related_name
Therelated_nameattribute defines how you access related objects from the reverse side of a ForeignKey relationship.Step 2: Identify what related_name affects
It does not affect table names, primary keys, or ordering but sets the attribute name for reverse access.Final Answer:
It sets the name used to access related objects from the other model. -> Option AQuick Check:
related_name = reverse access name [OK]
Hint: related_name names reverse access from related model [OK]
Common Mistakes:
- Confusing related_name with table name
- Thinking it sets primary key
- Assuming it controls query ordering
2. Which of the following is the correct way to set a
related_name in a Django ForeignKey field?easy
Solution
Step 1: Recall correct attribute name
The correct attribute to set reverse access name isrelated_name.Step 2: Check syntax correctness
author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE) usesrelated_name='books'correctly; others use incorrect attribute names.Final Answer:
author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE) -> Option CQuick Check:
Use related_name= for reverse access [OK]
Hint: Use exact attribute name 'related_name' in ForeignKey [OK]
Common Mistakes:
- Using 'related' instead of 'related_name'
- Using 'reverse_name' or 'relation_name' which don't exist
- Missing on_delete argument
3. Given these models:
What will
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE)
title = models.CharField(max_length=100)What will
author.books.all() return?medium
Solution
Step 1: Understand related_name usage
Therelated_name='books'allows accessing all Book objects from an Author instance usingauthor.books.Step 2: Interpret the method call
author.books.all()returns a queryset of all Book objects linked to that Author.Final Answer:
All Book objects related to that Author instance. -> Option BQuick Check:
author.books.all() = related books [OK]
Hint: related_name lets you get all related objects easily [OK]
Common Mistakes:
- Thinking it returns Author objects
- Assuming syntax error due to related_name
- Expecting empty queryset without data
4. Identify the error in this model definition:
What problem will this cause?
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='post', on_delete=models.CASCADE)
text = models.TextField()What problem will this cause?
medium
Solution
Step 1: Understand related_name uniqueness
Therelated_namemust be unique per model to avoid clashes.Step 2: Analyze the name 'post'
If Post model already has a field or reverse accessor named 'post', this causes a clash error.Final Answer:
It will cause a reverse accessor clash if Post already has a field named 'post'. -> Option DQuick Check:
related_name must be unique to avoid clashes [OK]
Hint: Avoid related_name same as model or field names [OK]
Common Mistakes:
- Assuming related_name can be any string without conflict
- Thinking related_name causes syntax error
- Believing TextField is invalid here
5. You have these models:
You want to access all products of a category using
class Category(models.Model):
name = models.CharField(max_length=50)
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)You want to access all products of a category using
category.items.all(). How should you modify the ForeignKey?hard
Solution
Step 1: Understand reverse access naming
To usecategory.items.all(), the ForeignKey must haverelated_name='items'.Step 2: Check other options
Changing to ManyToManyField or renaming the field won't create the desired reverse attribute.related_query_nameaffects query filters, not attribute names.Final Answer:
Add related_name='items' to the ForeignKey in Product. -> Option AQuick Check:
related_name sets reverse attribute name [OK]
Hint: Set related_name='items' to get category.items [OK]
Common Mistakes:
- Confusing related_name with related_query_name
- Changing field name instead of related_name
- Switching to ManyToManyField unnecessarily
