One To One Relationship
Let’s learn how to make One-to-One relationships between Django models.
We'll cover the following...
OneToOneField
field
This field is used for a One-to-One relationship. To understand how this relationship between models works, we don’t need to add another model. We will use our existing models:
- Company
- Employee
- Projects
Now, the new relationship we are adding is that one project will have only one employee as a Team Lead. Similarly, one employee will be the Team Lead for only one project. This makes it a One-to-One relationship. This relationship is shown in the following illustration:
The implementation of the models will be the following:
Press + to interact
from django.db import modelsfrom datetime import date# Create your models here.class Company(models.Model):name = models.CharField(max_length=264,unique=True)number_of_employees= models.IntegerField(default=0)def __str__(self):return self.nameclass Employee(models.Model):employee_name = models.CharField(max_length=264, unique= True)company_name = models.ForeignKey(Company, on_delete=models.CASCADE)date_of_birth = models.DateField(default= date.today)def __str__(self):return self.employee_nameclass Project(models.Model):project_name = models.CharField(max_length=264, unique= True)employee_name = models.ManyToManyField('Employee')team_lead = models.OneToOneField('Employee', on_delete=models.CASCADE, related_name='team_lead')def __str__(self):return self.project_name
In the ...