ManyToMany Relationship Example

A snippet showing how to set up a ManyToMany relationship in Django models.


# models.py

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Course(models.Model):
    title = models.CharField(max_length=200)
    students = models.ManyToManyField(Student, related_name='courses')

    def __str__(self):
        return self.title
  

# Django Shell

>>> from school.models import Student, Course
>>> s1 = Student.objects.create(name='Alice')
>>> s2 = Student.objects.create(name='Bob')
>>> course = Course.objects.create(title='Math 101')
>>> course.students.add(s1, s2)
>>> course.students.all()
<QuerySet [<Student: Alice>, <Student: Bob>]>
>>> s1.courses.all()
<QuerySet [<Course: Math 101>]>
  
Explanation:
  • ManyToManyField represents a many-to-many relationship (e.g., students enrolled in multiple courses).
  • Django automatically creates a join table to manage the relationships between students and courses.
  • The related_name attribute lets you query reverse relationships (e.g., student.courses.all()).
  • Useful in real-world cases like tags on articles, students in courses, or users in groups.
  • Category Models & ORM
  • Total Views 622
  • Last Modified 20 September, 2025
  • Tags #models #relationships #m2m #orm
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.