Full answer
A student can attend many courses and a course has many students. Django models this with one field on either side: courses = models.ManyToManyField(Course, related_name="students"). The migration creates a table with two foreign keys and a unique pair.
API on the manager: student.courses.add(c1, c2), remove(c1), set([c1, c3]) (replaces the whole set), clear(), and student.courses.filter(...). The reverse side is course.students.all().
Extra data needs a through model:
class Enrolment(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
joined = models.DateField()
grade = models.CharField(max_length=2, blank=True)
courses = models.ManyToManyField(Course, through="Enrolment")Since Django 2.2 you may call add(), set() and create() on a through relationship if you pass through_defaults={"joined": ...}. Before that, you had to create Enrolment rows directly, which still works and is often clearer.
Decide at the start: switching a plain M2M to a through model later is painful because the join table must be migrated by hand. Add a UniqueConstraint on the pair in the through model to prevent duplicates, and use prefetch_related("courses") to avoid N+1 queries when listing.
Self-referential M2M (friends) uses ManyToManyField("self", symmetrical=True).
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
class Course(models.Model):
title = models.CharField(max_length=40)
class Meta:
app_label = "school"
class Student(models.Model):
name = models.CharField(max_length=40)
courses = models.ManyToManyField(Course, through="Enrolment", related_name="students")
class Meta:
app_label = "school"
class Enrolment(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
grade = models.CharField(max_length=2, blank=True)
class Meta:
app_label = "school"
constraints = [models.UniqueConstraint(fields=["student", "course"], name="one_enrolment_per_pair")]
with connection.schema_editor() as editor:
for m in (Course, Student, Enrolment):
editor.create_model(m)
asha, ravi = Student.objects.create(name="Asha"), Student.objects.create(name="Ravi")
db, net = Course.objects.create(title="DBMS"), Course.objects.create(title="Networks")
asha.courses.add(db, net, through_defaults={"grade": "A"})
ravi.courses.add(db)
print([c.title for c in asha.courses.all()])
print(sorted(s.name for s in db.students.all()))
print(Enrolment.objects.get(student=asha, course=db).grade)
asha.courses.set([net])
print([c.title for c in asha.courses.all()])
print(Student.objects.prefetch_related("courses").get(name="Ravi").courses.count())
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['DBMS', 'Networks'] ['Asha', 'Ravi'] A ['Networks'] 1
Key points
- M2M creates a join table; both sides get manager methods
- set() replaces, add() appends, clear() empties
- Use through= when the link carries data
- Add a unique constraint on the pair; prefetch_related avoids N+1
Common mistakes
- Choosing a plain M2M and later needing extra columns
- Forgetting a unique constraint on the pair in a through model
- Looping over students and querying courses each time instead of prefetch_related
- Using add() on a through model without through_defaults for required fields
Follow-ups
- How do you convert an existing M2M to a through model without losing data?
- How do you query students who take both DBMS and Networks?
- What happens to the join rows when a student is deleted?
Tips
- Explain the hidden join table
- Give an example of a through model
- Mention N+1 and prefetch_related