Performance: ManyToManyField for many-to-many
This affects database query performance and page load speed when rendering related data in templates.
Jump into concepts and practice - no test required
books = Book.objects.prefetch_related('authors').all() # In template same as above
class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField('Author') # In view books = Book.objects.all() # In template {% for book in books %} {{ book.title }} {% for author in book.authors.all() %} {{ author.name }} {% endfor %} {% endfor %}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Without prefetch_related | N+1 queries cause delayed data rendering | Multiple reflows possible if data loads incrementally | Higher paint cost due to slower data availability | [X] Bad |
| With prefetch_related | 2 queries total, data ready before render | Single reflow after full data load | Lower paint cost, faster LCP | [OK] Good |
ManyToManyField in Django represent?class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
# Assume authors and books are created and linked properly
book = Book.objects.get(title='Django Guide')
authors = book.authors.all()authors contain?book.authors.all() returns a QuerySet of all Author objects related to that Book.authors holdsclass Student(models.Model):
name = models.CharField(max_length=50)
courses = models.ManyToManyField('Course')
class Course(models.Model):
title = models.CharField(max_length=100)
# Usage
student = Student(name='Alice')
student.courses.add(1)add() method requires the parent instance (Student) to be saved first.student = Student(name='Alice') creates an unsaved instance; call student.save() before student.courses.add(1).ManyToManyField?