Performance: Related name for reverse access
This affects database query efficiency and template rendering speed when accessing related objects in Django ORM.
Jump into concepts and practice - no test required
class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books') # Accessing books from author with related_name books = author.books.all()
class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) # Accessing books from author without related_name books = author.book_set.all()
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Default reverse accessor (book_set) | N/A | N/A | N/A | [!] OK - can cause multiple DB queries |
| Custom related_name with prefetch_related | N/A | N/A | N/A | [OK] Good - single optimized DB query |
related_name attribute do in a Django model's ForeignKey field?related_name attribute defines how you access related objects from the reverse side of a ForeignKey relationship.related_name in a Django ForeignKey field?related_name.related_name='books' correctly; others use incorrect attribute names.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)author.books.all() return?related_name='books' allows accessing all Book objects from an Author instance using author.books.author.books.all() returns a queryset of all Book objects linked to that Author.class Comment(models.Model):
post = models.ForeignKey(Post, related_name='post', on_delete=models.CASCADE)
text = models.TextField()related_name must be unique per model to avoid clashes.class Category(models.Model):
name = models.CharField(max_length=50)
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)category.items.all(). How should you modify the ForeignKey?category.items.all(), the ForeignKey must have related_name='items'.related_query_name affects query filters, not attribute names.