Course Content
DJANGO Tutorial
About Lesson

Relationships between models (One-to-One, One-to-Many, Many-to-Many)

Django, a high-level web framework for Python, empowers developers to create robust and scalable web applications. One of its key features is the Object-Relational Mapping (ORM) system, which allows you to define relationships between models. In this post, we’ll delve into the intricacies of different relationships in Django models: One-to-One, One-to-Many, and Many-to-Many.

One-to-One Relationship

The One-to-ne relationship in Django models signifies a unique and direct association between two entities. This relationship is established using the OneToOneField. For instance, consider a scenario where each Person has exactly one Profile. The models would look like:

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

class Profile(models.Model):
person = models.OneToOneField(Person, on_delete=models.CASCADE)
bio = models.TextField()

Here, each person has a single profile, and vice versa.

One-to-Many Relationship

The One-to-Many relationship is a fundamental concept where one entity can be associated with multiple instances of another. This is achieved using the ForeignKey field. Let’s take the example of  Category having multiple Products:

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

class Product(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=5, decimal_places=2)

In this case, a category can have numerous products, but each product belongs to only one category.

Many-to-Many Relationship

In Django, the Many-to-Many relationship is used when multiple instances of one model can be associated with multiple instances of another. This is accomplished using the ManyToManyField. Consider a scenario where Student can enroll in multiple Courses, and a Course can have multiple students:

class Student(models.Model):
name = models.CharField(max_length=100)
courses = models.ManyToManyField('Course')

class Course(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()

Here, a student can enroll in multiple courses, and a course can have multiple students.