Django Models with Relationships — One to One Relationship

Hello all. I this blog I am explaining what is a One-to-One Relationship and how to perform it in Django.

Cover Image. Ignore it.

In my previous blog, I have explained what is relationships and the types of it. Do visit it.

What is a relationship and What is a one-to-one relationship?

As said, a relationship is an association between two entities. A relationship allows us to spit and store the data in different databases. The relationship works between two Relational Database Models.

A One-to-One relationship is a type of Relationship where both tables can have only one record on either side. A one-to-one relationship is like a relationship between a husband and a wife.

Now let’s see how does the relationship works with Django. Let’s start.

  1. Create a Django Project and Adhar app

Now let’s create our Django project. The below commands create a Django project and migrate the changes to the database.

Once done, check if the server is working well. Then just create a Django app within our Django Project where we will be creating our model.

Once done, do all the necessary steps for registering our app to our Django project as I did below.

djRelation/settings.py

Create a urls.py file in our app adhar and make sure the file should look like this.

To demonstrate this example, we need no URL. We can perform it in the Django shell itself. So I am not adding any URL here. After creating this file, just map the adhar/urls.py to the djRelation/urls.py file.

djRelation/urls.py

2. Crafting our Ahdar Model

I am creating two models, Person and Adhar where the primary key (id)of the model Person will be an OneToOneField of Adhar.

adhar/models.py

Now just migrate.

3. Adding values to the Model

Let’s start our shell now. Now I am inserting some value to both tables. While inserting data to the Adhar table, make sure the person field should be an instance of thePerson table. Otherwise, it will through error.

Now I am trying to add another Adhar data where I am be trying to use the Person instance p1 which has been already related to another Adhar.

This will through Integrity Error.

In my previous blog, I have explained the basics of Relationship and its types.

In my next blog, I am explaining how to perform many-to-one relationships with Django. Stay connected.

Feel free to contact me for any queries.

Email: sjlouji10@gmail.com

Linkedin: https://www.linkedin.com/in/sjlouji/

Complete Code can be found on my Github: https://github.com/sjlouji/Medium-Django-Model-Relationships.git

Happy coding…

Software Engineer