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.

Practice

Objective:
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 models.py

Create the PersonalInfo model in the models.py 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.

employee_learning/models.py
 :
class Employee(models.Model):
 :

class PersonalInfo(models.Model):
    name=models.OneToOneField(Employee, on_delete=models.CASCADE, primary_key=True)
    tel=models.CharField(max_length=15)
    address=models.CharField(max_length=50)

2. Add Personal Info model in admin.py

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

employee_learning/admin.py
from .models import Employee
from .models import Division
from .models import PersonalInfo

admin.site.register(Employee)
admin.site.register(Division)
admin.site.register(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 manage.py makemigrations employee_learning
python manage.py migrate
python manage.py 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