Performance: Model relationships preview
This affects page load speed and interaction responsiveness by controlling how related data is fetched and rendered.
books = Book.objects.select_related('author').all() for book in books: print(book.author.name)
for book in books: print(book.author.name)
| Pattern | Database Queries | Query Count | Page Load Impact | Verdict |
|---|---|---|---|---|
| Access related data without select_related | Multiple queries per item | N+1 queries | Slower load and interaction | [X] Bad |
| Use select_related for foreign keys | Single joined query | 1 query | Faster load and interaction | [OK] Good |
ForeignKey for many-to-one, OneToOneField for one-to-one, and ManyToManyField for many-to-many relationships.ForeignKey field connects many instances of one model to a single instance of another model, representing many-to-one.OneToOneField is used to create a one-to-one link between two models.profile = models.OneToOneField(User, on_delete=models.CASCADE) correctly defines a one-to-one relationship with proper arguments.class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)book.author.name return if book is a Book instance?book.author gives the Author instance linked to the book.book.author.name accesses the name attribute of the related Author instance, returning the author's name.class Profile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField()on_delete argument for relationship fields like OneToOneField to specify behavior on deletion.on_delete=models.CASCADE or similar, which causes an error.ManyToManyField('self', symmetrical=False, related_name='following') correctly models directed follow relationships.Pass the test and this pattern moves unknown