Hello all. I this blog I am explaining what is a One-to-One Relationship and how to perform it in Django.
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.
- 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.
$ django-admin startproject djRelation
$ cd djRelation/
$ python3 manage.py migrate
$ python3 manage.py runserver
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.
$ python3 manage.py startapp adhar
Once done, do all the necessary steps for registering our app to our Django project as I did below.
djRelation/settings.py
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'adhar', # add this line
]
Create a urls.py
file in our app adhar
and make sure the file should look like this.
from django.conf.urls import url, include
from django.urls import pathurlpatterns = []
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
from django.conf.urls import url, include
from django.urls import path
from django.contrib import adminurlpatterns = [
url(r'^admin/', admin.site.urls),
path('adhar/',include('adhar/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
from django.db import models# Create your models here.
class Person(models.Model):
name = models.TextField(max_length=100)
email = models.EmailField()
mobile = models.TextField(max_length=100)class Adhar(models.Model):
person = models.OneToOneField("Person",on_delete=models.CASCADE)
signature = models.TextField()
adhar_no = models.TextField(max_length=100)
Now just migrate.
$ python3 manage.py makemigrations
$ python3 manage.py 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.
$ python3 manage.py shellIn [1]: from adhar.models import PersonIn [2]: p1 = Person(name="Joan louji", email="sjlouji10@gmail.com", mobile="123412")
In [3]: p1.save()In [4]: p2 = Person(name="Rion", email="rion@gmail.com", mobile="0987632")
In [5]: p2.save()In [6]: from adhar.models import AdharIn [7]: a1 = Adhar(person=p1, signature="asdf234dsafuiq3&^$^GUJHVR", adhar_no="432198176354")
In [8]: a1.save()In [9]: a2 = Adhar(person=p2, signature="adfpoiwruywqtrgmnb13241)*&^%$", adhar_no="2314928376")
In [10]: a2.save()In [11]: p = Person.objects.all()
In [12]: print(p)<QuerySet [<Person: Person object (1)>, <Person: Person object (2)>]>In [13]: a = Adhar.objects.all()
In [14]: print(a)<QuerySet [<Adhar: Adhar object (1)>, <Adhar: Adhar object (2)>]>In [15]: a.values()Out[16]: <QuerySet [{'id': 1, 'person_id': 1, 'signature': 'asdf234dsafuiq3&^$^GUJHVR', 'adhar_no': '432198176354'}, {'id': 2, 'person_id': 2, 'signature': 'adfpoiwruywqtrgmnb13241)*&^%$', 'adhar_no': '2314928376'}]>
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 [17]: a3 = Adhar(person = p1, signature = "1234lkjhjgfjgk*(&^%$", adhar_no="1234124")
In [18]: a3.save()IntegrityError: UNIQUE constraint failed: adhar_adhar.person_id
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…