Skip to content
devtoolbox.cc

Django · Chapter 6 of 8

Django relationships: ForeignKey, ManyToMany, N+1 queries

11 min study · Examples checked with Django 6.1 on Python 3.14 ·

Data is rarely one table. Lessons belong to courses, lessons carry several tags, and learners enroll in courses. Django models express these links with three kinds of relation fields, and the ORM follows them in both directions. This chapter adds courses, tags and enrollments to the catalog, shows how to query across the links, what happens on delete, and how to avoid the most common performance problem in ORM code: running one query per row.

Three kinds of relationship

Relationship Field Example
Many-to-one ForeignKey on the “many” side Each lesson belongs to one course; a course has many lessons
Many-to-many ManyToManyField on either side A lesson has many tags; a tag is on many lessons
One-to-one OneToOneField Each user has at most one learner profile

A ForeignKey is a column holding the other row’s ID. A many-to-many relation needs a separate join table, which Django creates for you, or which you define yourself as a “through” model when the link carries its own data, such as the date someone joined a course.

Add the models

In catalog/models.py, import settings (from django.conf import settings) and add Course and Tag above Lesson:

class Course(models.Model):
    title = models.CharField(max_length=120, unique=True)
    learners = models.ManyToManyField(
        settings.AUTH_USER_MODEL, through="Enrollment", related_name="courses", blank=True
    )

    def __str__(self) -> str:
        return self.title


class Tag(models.Model):
    name = models.SlugField(max_length=40, unique=True)

    def __str__(self) -> str:
        return self.name

Give Lesson two new fields, after created_at:

    course = models.ForeignKey(
        Course, on_delete=models.PROTECT, related_name="lessons", null=True, blank=True
    )
    tags = models.ManyToManyField(Tag, related_name="lessons", blank=True)

And add the enrollment model at the end:

class Enrollment(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    learner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    joined_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=["course", "learner"], name="one_enrollment_per_course"),
        ]

Then run makemigrations and migrate. settings.AUTH_USER_MODEL refers to Django’s user model, or a custom one if the project defines it; always refer to users this way rather than importing User directly. related_name names the reverse direction: course.lessons lists a course’s lessons and user.courses a user’s courses. The course link is nullable because the lessons created in earlier chapters have no course yet.

Use the relations

python = Course.objects.create(title="Python")
loops = Lesson.objects.create(title="Loops", minutes=21, course=python, published=True)
loops.tags.add(basics, core)

loops.course.title                         # 'Python'
[t.name for t in loops.tags.all()]         # ['basics', 'core']
python.lessons.values_list("title", flat=True)
# ['Functions', 'Loops', 'Variables']
Lesson.objects.filter(course__title="Python", tags__name="core")      # <Lesson: Loops>
Course.objects.annotate(n=Count("lessons")).values_list("title", "n")
# [('Python', 3), ('Web', 1)]

Enrollment.objects.create(course=python, learner=ada)
ada.courses.all(), python.learners.count()  # [<Course: Python>], 1

The forward side reads like an attribute (loops.course) and the reverse side is a manager (python.lessons) with the full query API. A double _ follows a relation inside a filter, course__title, any number of levels deep, and the ORM writes the joins. tags.add(), remove(), set() and clear() manage many-to-many links. With a through model, create rows of the through model directly, as with Enrollment, so its extra fields get values. Its unique constraint stops a learner from joining the same course twice:

IntegrityError: UNIQUE constraint failed: catalog_enrollment.course_id, catalog_enrollment.learner_id

What happens on delete

on_delete decides what happens to lessons when their course is deleted, and it is a business decision, not a technical one:

  • CASCADE deletes the lessons too. Right for enrollments: without the course they mean nothing.
  • PROTECT refuses to delete the course while lessons point at it. web.delete() raised ProtectedError: 1 lesson(s) still use it, which forces someone to move or delete the lessons deliberately.
  • SET_NULL keeps the lessons and clears the link; the field must allow null.
  • RESTRICT is like PROTECT but allows the delete when the lessons are deleted in the same operation through another cascade.

A one-to-one link behaves like a ForeignKey with a unique constraint. Accessing a missing reverse side, such as user.profile for a user without a profile, raises RelatedObjectDoesNotExist rather than returning None, so check with hasattr or query the profile model directly.

The N+1 problem

Templates that loop over lessons and print lesson.course.title hide a trap: each access to lesson.course runs a separate query. One query for the list plus one per row is called the N+1 problem, and with 50 rows it is 51 queries. Measured on four lessons:

[l.course.title for l in Lesson.objects.all()]                         # 5 queries
[l.course.title for l in Lesson.objects.select_related("course")]      # 1 query
[[t.name for t in l.tags.all()] for l in Lesson.objects.prefetch_related("tags")]  # 2 queries

select_related follows ForeignKey and one-to-one links with a SQL join, in the same query. prefetch_related handles many-to-many and reverse relations: it loads all related rows in one extra query and matches them up in Python. Add them in the view that builds the QuerySet, for example Lesson.objects.filter(published=True).select_related("course").prefetch_related("tags") in home. To find N+1 problems, watch the query count: Django’s test framework has assertNumQueries, and the third-party Django Debug Toolbar shows every query for a page.

Practice

Add a LearnerProfile with a OneToOneField to the user model (related_name="profile") and a weekly_goal_minutes field. Then write a query for the courses a given user is enrolled in, each with its number of published lessons, and check how many queries it takes.

Answer check: user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile"). The course query is ada.courses.annotate(n=Count("lessons", filter=Q(lessons__published=True))), which runs as a single query because the count happens in SQL. Register the new models in the admin to edit them.

Summary

ForeignKey links many rows to one, ManyToManyField links many to many (with a through model when the link has data), and OneToOneField links one to one. related_name names the reverse side, double-_ lookups follow relations in filters, and on_delete encodes what deletion means. Prevent N+1 queries with select_related for single links and prefetch_related for collections.

All Django chapters