Django Models – OneToOneField

To make a One-To-One relationship, Django uses OneToOneField. Just like in ForeignKey, there are two key arguments you need to specify.

  1. Related model name
  2. On_delete argument

In addition to these arguments, you may need to add the primary_key option for the field.


Learn how to use OneToOneField

In this practice, we'll explain how to use OneToOneField. In this case example, we'll create a new model PersonalInfo and connect it with the Employee model using One-To-One relationship.

1. Add Personal Info model in

Create the PersonalInfo model in the file with OneToOneField to connect with the Employee model.

Add the model after the Employee model, as the PersonalInfo model refers to the Employee model. Below is the code for the PersonalInfo model.

The yellow lines below are the new code.

class Employee(models.Model):

class PersonalInfo(models.Model):
    name=models.OneToOneField(Employee, on_delete=models.CASCADE, primary_key=True)

2. Add Personal Info model in

You need to add the new model in the file to reflect the model.

from .models import Employee
from .models import Division
from .models import PersonalInfo

3. Execute the changes in the database and check the admin site

Run the three usual commands and go to the Django admin site.

Command Line - INPUT
python makemigrations employee_learning
python migrate
python runserver

You can see that the PersonalInfo model is added and connected with the Employee model.

Django Models – OneToOneField

As we set the primary key for the OneToOne relationship field, you'll encounter an error message when you try to register personal info for the same employee twice.

Django Models – OneToOneField Error Message