Difference between One-to-one, Many-to-many, and Many-to-one Relationships in Django

 

One-to-one Relationship

Here two objects must have a single/unique relationship with one another. Take for example a Student and Student_profile, two students can’t have the same profile.

from django.db import models

class Student(models.Model):
name = models.CharField(max_length=50)
student_id = models.CharField(max_length=80)

def __str__(self):
return self.name

class Student_Profile(models.Model):
student = models.OneToOneField(
student,
on_delete=models.CASCADE,
)
student_id= models.CharField(max_length=80)

def __str__(self):
return self.student.name

Many-to-many Relationship

Here 0 or more objects in one model can be related to zero or more objects in another model, Yeah, it’s that simple. Take for example a relationship between a doctor and a patient, a doctor can treat zero or more patients. In the same way, a patient can be treated by 0 or more doctors.

class Doctor(models.Model):
name = models.CharField(max_length=150)
def __str__(self):
return self.name

class Patient(models.Model):
doctors = models.ManyToManyField(Doctor)
name = models.CharField(max_length=150)
def __str__(self):
return self.name

Many-to-one Relationships

The many-to-one relationship is known as foreign key relationship in Django, here 0 to many objects in one model may be related to one object in another model. A project can have more than one student working on it. In this example, I am going to compare the relationship between two entities Student and Project. A couple of students can be assigned a project for an assignment or something.

class Student(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)

def __str__(self):
return self.first_name

class Project(models.Model):
name = models.CharField(max_length=30)
sudents = models.ForeignKey(Student, on_delete=models.CASCADE)
def __str__(self):
return self.name
Previous
Next Post »