What is related_name used for in Django with code example?

In Django, the related_name attribute is used to create a reverse relationship between models when defining a ForeignKey, OneToOneField, or ManyToManyField. It allows you to specify the name of the reverse relationship from the related model back to the model that defines the field.

Here’s an example to illustrate the use of related_name:

Example Scenario: Consider a scenario where you have two models: Author and Book. An author can have multiple books, and a book can have a single author. You want to create a reverse relationship to access all the books by a specific author.

Step 1: Define the Models:

from django.db import models

class Author(models.Model):
name = models.CharField(max_length=100)

class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)

In this example, we have two models: Author and Book. The Book model has a ForeignKey field referencing the Author model.

Step 2: Use related_name: You can use the related_name attribute to create a reverse relationship from the Author model back to the Book model. This allows you to access all books by a specific author easily.

class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')

In the above code, we’ve added related_name='books' to the ForeignKey field. This means that from an instance of the Author model, you can access the books associated with that author using the books attribute.

Usage: Now you can use the related_name to access books by a specific author:

# Create an author
author = Author.objects.create(name='J.K. Rowling')

# Create books by the author
book1 = Book.objects.create(title='Harry Potter and the Sorcerer\'s Stone', author=author)
book2 = Book.objects.create(title='Harry Potter and the Chamber of Secrets', author=author)

# Access books using the related_name
books_by_author = author.books.all()
for book in books_by_author:
print(book.title)

In this example, you use the books attribute on an Author instance to retrieve all books written by that author.

Using related_name improves the clarity of your code and makes it easier to navigate the relationships between models in both directions. It’s particularly useful when dealing with reverse relationships.