TExcelTAD
Home › Django › Django Many-to-Many

Django Many-to-Many

Some relationships are many on both sides: a student takes many courses and a course has many students; an article has many tags and a tag labels many articles. A single foreign-key column can't express that. Databases use a third junction table with one row per link, and Django creates it for you when you declare a ManyToManyField.

python
class Tag(models.Model):
    name = models.CharField(max_length=30)

class Article(models.Model):
    title = models.CharField(max_length=100)
    tags = models.ManyToManyField(Tag, related_name="articles", blank=True)

Put the field on either model (whichever reads more naturally); the relation is accessible from both sides.

Adding and removing links

A many-to-many field gives you a related manager with methods to manage links. The objects must be saved first, because the junction table stores their ids:

Method Effect
article.tags.add(t1, t2) create links (duplicates are ignored)
article.tags.remove(t1) delete a link (the tag itself stays)
article.tags.set([t1, t3]) make the links exactly this list
article.tags.clear() remove all links
article.tags.all() / .filter() / .count() query the linked objects
article.tags.create(name="x") create a new Tag and link it
python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["demo"] = types.ModuleType("demo")      # stand-in for a demo/ app package
sys.modules["demo"].__file__ = "demo/__init__.py"
settings.configure(INSTALLED_APPS=["demo"],
                   DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection

class Tag(models.Model):
    name = models.CharField(max_length=30)
    class Meta:
        app_label = "demo"
    def __str__(self):
        return self.name

class Article(models.Model):
    title = models.CharField(max_length=100)
    tags = models.ManyToManyField(Tag, related_name="articles", blank=True)
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Tag)
    editor.create_model(Article)       # also creates the junction table
print(sorted(connection.introspection.table_names()))

python, web, orm = (Tag.objects.create(name=n) for n in ["python", "web", "orm"])
post = Article.objects.create(title="Django in 10 minutes")

def tags():
    return [t.name for t in post.tags.order_by("name")]

post.tags.add(python, web)
print("add:   ", tags())
post.tags.add(python)                  # already linked: ignored
post.tags.remove(web)
print("remove:", tags())
post.tags.set([web, orm])
print("set:   ", tags())
post.tags.create(name="tutorial")
print("create:", tags())
post.tags.clear()
print("clear: ", tags(), "| tags still exist:", Tag.objects.count())
['demo_article', 'demo_article_tags', 'demo_tag']
add:    ['python', 'web']
remove: ['python']
set:    ['orm', 'web']
create: ['orm', 'tutorial', 'web']
clear:  [] | tags still exist: 4

The junction table demo_article_tags holds pairs of (article_id, tag_id).

Querying both directions

The reverse side uses the related_name (or article_set by default). Lookups span the relation with double underscores, just like foreign keys:

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["demo"] = types.ModuleType("demo")
sys.modules["demo"].__file__ = "demo/__init__.py"
settings.configure(INSTALLED_APPS=["demo"],
                   DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.db.models import Count

class Tag(models.Model):
    name = models.CharField(max_length=30)
    class Meta:
        app_label = "demo"

class Article(models.Model):
    title = models.CharField(max_length=100)
    tags = models.ManyToManyField(Tag, related_name="articles")
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Tag)
    editor.create_model(Article)

t = {n: Tag.objects.create(name=n) for n in ["python", "web", "orm", "css"]}
data = {"Django ORM tips": ["python", "orm"], "Flexbox basics": ["web", "css"],
        "Views and URLs": ["python", "web"], "Raw SQL vs ORM": ["orm"]}
for title, names in data.items():
    Article.objects.create(title=title).tags.set([t[n] for n in names])

print([a.title for a in t["python"].articles.order_by("title")])
print([a.title for a in Article.objects.filter(tags__name="web").order_by("title")])
print([a.title for a in Article.objects.filter(tags__name__in=["python", "orm"]).distinct().order_by("title")])

popular = Tag.objects.annotate(n=Count("articles")).order_by("-n", "name")
print([(tag.name, tag.n) for tag in popular])
['Django ORM tips', 'Views and URLs']
['Flexbox basics', 'Views and URLs']
['Django ORM tips', 'Raw SQL vs ORM', 'Views and URLs']
[('orm', 2), ('python', 2), ('web', 2), ('css', 1)]

Without .distinct(), "Django ORM tips" would appear twice in the third query, because it matches both python and orm.

Extra data on the link: through models

Sometimes the link itself has data — the date a student enrolled, or their grade. Then you define the junction table yourself as a model and point to it with through:

python · try it yourself
import sys, types, django, datetime
from django.conf import settings
sys.modules["demo"] = types.ModuleType("demo")
sys.modules["demo"].__file__ = "demo/__init__.py"
settings.configure(INSTALLED_APPS=["demo"],
                   DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection

class Student(models.Model):
    name = models.CharField(max_length=30)
    class Meta:
        app_label = "demo"

class Course(models.Model):
    title = models.CharField(max_length=50)
    students = models.ManyToManyField(Student, through="Enrollment", related_name="courses")
    class Meta:
        app_label = "demo"

class Enrollment(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)
    class Meta:
        app_label = "demo"
        unique_together = [("student", "course")]

with connection.schema_editor() as editor:
    for model in (Student, Course, Enrollment):
        editor.create_model(model)

an, binh = Student.objects.create(name="An"), Student.objects.create(name="Binh")
django_course = Course.objects.create(title="Django 101")
Enrollment.objects.create(student=an, course=django_course, joined=datetime.date(2026, 9, 1), grade="A")
django_course.students.add(binh, through_defaults={"joined": datetime.date(2026, 9, 15)})

print([s.name for s in django_course.students.order_by("name")])
for e in Enrollment.objects.filter(course=django_course).select_related("student").order_by("joined"):
    print(e.student.name, e.joined, e.grade or "-")
print([c.title for c in binh.courses.all()])
['An', 'Binh']
An 2026-09-01 A
Binh 2026-09-15 -
['Django 101']

add(), set() and create() still work with a custom through model; required extra fields are supplied with through_defaults.

Tip: Start with a plain ManyToManyField. If you later need extra columns, you can migrate to a through model — but it's easier to choose it from the start if you suspect the link will carry data.

Test yourself

What does Django create for a ManyToManyField?

  1. A column on each table
  2. A junction table holding pairs of ids
  3. A JSON field
  4. Nothing; it's computed in Python

What does article.tags.remove(tag) do?

  1. Deletes the tag from the database
  2. Removes only the link between the article and the tag
  3. Deletes the article
  4. Removes all tags

When do you need a through model?

  1. Always
  2. When the relationship itself has extra data, like an enrollment date
  3. When using ForeignKey
  4. Only on PostgreSQL