0
0
Djangoframework~5 mins

Related name for reverse access in Django

Choose your learning style9 modes available
Introduction

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.

You want to get all comments related to a blog post.
You want to find all orders made by a customer.
You want to list all books written by an author.
You want to access all tasks assigned to a project.
You want to retrieve all messages sent by a user.
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
You can access all books of an author by 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)
Use 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()
Access all tasks of a project with 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()])
OutputSuccess
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.