Django One-To-One Relations

Srivastava
4 min readAug 19, 2021

Want to learn about Django Models One To One Relationship 🤔…? Here is the complete guide for you😌.

Django Models are the class that represents the table or collections stored in our database. Each attribute of the class is a field of the table.

Connecting different tables of database, Django provides the three most common Model relationships

  • One-To-One Model relationship
  • Many-To-One Model Relationship
  • Many-To-Many Model Relationship

What is One-To-One Relationship in Models

As the name suggest One-To-One Relationship means relation of one database table with another table that is they can have only one record on either side of the relation.

For Example:-

  • Person with unique id
  • Husband Wife
  • CEO of the Company

Let’s create two models Person and Uid

After creating models don’t forget to migrate them.

To do so enter the following commands in the terminal.

python manage.py makemigrations
python manage.py migrate

Now let’s test for, the one to one relations between our models.

Add some values to both the tables, either by admin panel or by using Django shell

Added from Django Admin Panel

For adding values to tables using Django shell, run

python manage.py shell

You’re now in Django’s interactive console. It’s just like the Python prompt, but with some additional Django features. All the Python commands can be run here .

Till now we had made uid for individual persons. Let’s make another uid for existing person (say for Mr. Nobita)

new_uid_N= Uid(name=new_person1,signature="frsgyhnCR@#$")
new_uid_N.save()

Running this throws Integrity Error

return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: one_to_one_uid.name_id

Error shown on Admin Panel

It simply says that the Uid data for Nobita is already created, as the relation between the two tables is one to one.

OneToOneField

To define a one-to-one relation between models tables OneToOneField Field type is used. It requires positional argument, the class to which model is related.

syntax:

OneToOneField(to, on_delete, **options)

  1. to — The class to which model is related. Likewise in our case(Person)
  2. on_delete — It is simply used to delete the table value or column value if the parent table is deleted.

Mainly used values for on_delete in one_to_one relation are

  • CASCADE — Deletes the object containing ForeginKey (in our case if Person value is deleted its respective Uid value will also be deleted from the database)
  • PROTECT — Prevents the deletion of the referenced object by raising ProtectedError, that is if person (Nobita) is deleted then uid column for Nobita will not be deleted from database.
  • limit_choices_to — To limit deletions to some conditions

One-To-One Reverse Relation

So far we have seen that when the parent model (Person) is deleted child model (Uid) is deleted (CASCADE) or protected (PROTECT).

Now consider a situation where you want to delete the parent model (Person)if the child model (Uid) is deleted, there comes the reverse relation.

To do so Django provides signals that allow us to associate events with actions. Signals allow sender to notify a set of receivers that some action has taken place.

Types of Signals in Django

  • Login/Logout signals
  • Model Signals
  • Request/Response Signals
  • Test Signals
  • Database Wrappers

Make a signal.py file in your app folder

Now move to apps.py file in your app folder and make a ready function inside your One_to_oneConfig class

class One_to_oneConfig(AppConfig):
 ....
def ready(self):
import <app_name>.signals #importing signal.py file

navigate to __init__.py file in app folder add

default_app_config =’one_to_one.apps.One_to_oneConfig'

save all and try deleting values of Uid model and check whether the linked value of Person model is deleted or not.

If everything is done accordingly then for sure it will be deleted.🙌

--

--