Django’s default ManyToMany relationship only stores a pair of foreign keys, with no room for data that belongs to the relationship itself. When you need to store an enrollment date, a grade, or a role, declare an intermediate model (a through model) and point ManyToManyField at it with the through parameter. This keeps the familiar many-to-many API intact, while giving you a real model to query.
The Problem
Take a course site: a student enrolls in many courses, and a course has many students — a classic ManyToMany. But you also want to know when each student enrolled and what grade they got. The intermediate table Django creates automatically has only two foreign-key columns, with no room for an enrollment date or a grade. Stuffing the grade into the Student model is wrong, because the grade belongs to each student–course pair, not to the student alone.
class Student(models.Model): name = models.CharField(max_length=100)class Course(models.Model): title = models.CharField(max_length=200) students = models.ManyToManyField(Student)
The code above works fine, but course.students.add(student) can only create a “bare” link — it cannot store an enrollment date or a grade.
The Solution
Declare an Enrollment model as the intermediate table, then point ManyToManyField at it with the through parameter:
class Enrollment(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) enrolled_at = models.DateTimeField(auto_now_add=True) grade = models.FloatField(null=True, blank=True) class Meta: unique_together = [["student", "course"]]class Course(models.Model): title = models.CharField(max_length=200) students = models.ManyToManyField(Student, through="Enrollment")
Add unique_together on the foreign-key pair — a student cannot enroll in the same course twice, and this constraint blocks duplicates right at the database layer.
Create a link with extra data using through_defaults, or create it directly through the intermediate model:
course.students.add(student, through_defaults={"grade": 8.5})# more explicit when you need to set many fields:Enrollment.objects.create(student=student, course=course, grade=8.5)
Reverse queries also go through the through model, using the model’s lowercase name as the relation name:
# high-scoring enrollments for one coursecourse.enrollment_set.filter(grade__gte=8)# students scoring 9 or above in this courseStudent.objects.filter(enrollment__course=course, enrollment__grade__gte=9)
The familiar ManyToMany API stays intact: course.students.all(), student.course_set.all(), and prefetch_related("students") all work as before — the through model only adds data, it takes no feature away.
One caveat: if an extra field is required and has no default, calling .add() without through_defaults raises an IntegrityError. In that case, create the link directly with Enrollment.objects.create() to be explicit. If the through model has two foreign keys pointing at the same model, add through_fields so Django knows which pair of foreign keys forms the relationship.
Apply It to Your Project
The rule is simple: data that belongs to a pair goes in the through model, data that belongs to one side goes in that side’s model. Orders and products are the classic example — OrderItem stores the quantity and the price at the time of purchase, because the product’s price may change later but old invoices must not change with it. Similarly, team members should go through a Membership model to store their role and join date. Every time you are about to “temporarily squeeze” a field into a model, ask: does this field describe the object, or does it describe the relationship?
Related Posts
- Django: sửa lỗi N+1 query với prefetch_related cho quan hệ ManyToMany và quan hệ ngược
- Django: Remove Duplicate Records with distinct() When Filtering Across ManyToMany in 5 Minutes
- Django: truy vấn điều kiện phức tạp bằng Q object và cập nhật nguyên tử với F expression
Frequently Asked Questions
Once I use a through model, can I still use `.add()`?
Yes, as long as the extra fields have defaults or you pass through_defaults={...}. If a required extra field has no default, .add() will fail — then create the link directly through the through model.
The old intermediate table already has data — what happens when I switch to a through model?
Switching to a through model creates a new table. If the old data matters, write a data migration to copy it from the old table to the new one before deleting the old table. On a new project, just declare the through model from the start.
When should I NOT use a through model?
When the relationship only needs to store a pair of foreign keys and carries no data of its own, the default ManyToMany is simpler — Django creates the hidden intermediate table for you and you write no extra model. Only add a through model when the relationship genuinely carries data of its own.
💬 Have you tried this in your own project? If you hit an error or have a shorter way to do it, leave a comment below — I read them all and will add the best ideas to the post.
Sources
- Django documentation — “Extra fields on many-to-many relationships”: https://docs.djangoproject.com/en/6.1/topics/db/models/#extra-fields-on-many-to-many-relationships
- Django documentation — “ManyToManyField.through”: https://docs.djangoproject.com/en/6.1/ref/models/fields/#django.db.models.ManyToManyField.through
