This is our twentieth article in Django, in this article we are going to talk Django Models One-to-One Relationship.
a one to one relationship implies that one record is associated with another record. If you’re familiar with object-oriented programming, a one to one relationship in RDBMS is similar to object-oriented inheritance that uses this rule (e.g., a Car object is a Vehicle object). To define a one to one relationship in Django models you use the OneToOneField data type.
Flask Web Development Tutorials
1: Flask CRUD Application with SQLAlchemy
2: Flask Creating News Web Application
3: Flask Creating REST API with Marshmallow
Python GUI Development Tutorials
1: PyQt5 GUI Development Tutorials
2: Pyside2 GUI Development Tutorials
3: wxPython GUI Development Tutorials
4: Kivy GUI Development Tutorials
5: TKinter GUI Development Tutorials
So now we need to create a New Project in Django, also for django installation and creating New Project you can read this article Django Introduction & Installation. but you can use this command for creating of the New Project.
1 |
django-admin startproject ModelRelationship |
After creating of the Django Project, you need to migrate your project. make sure that you have changed the directory to the created project.
1 |
python manage.py migrate |
So after doing this, let’s create our Django App, i have already talked about Django App in one of my articles, you can check this Django Apps & URL Routing.
1 |
python manage.py startapp MyApp |
After creation of the App, you need to add the created App in your settings.py file
INSTALLED_APP section.
1 2 3 4 5 6 7 8 9 |
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MyApp', ] |
Also we need to create a super user, because we will use the django admin panel in this article,
you can use this command for creating of the super user.
1 |
python manage.py createsuperuser |
Now open your models.py in your MyApp App, and add your model, basically in this example we have two models the first one is Place model and the second one is Restaurant model, and we want to use Django Models One-to-One Relationship with our these two models.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): return self.name class Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=models.CASCADE, primary_key=True, ) serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) def __str__(self): return self.place.name |
The first Django Model is Place model, which has just name and address fields, the second model is Restaurant model which has the place field, that itself has models.OneToOneField(Place, on_delete=models.CASCADE, primary_key = True,) definition.
The models.OneToOneField() definition creates the one to one relationship, where the first argument Place indicates the relationship model. The second argument 0n_delete=models.CASCADE tells Django that in case the relationship record is deleted (i.e., the Place ,) its other record (i.e., the Restaurant ) will also be deleted, this last argument prevents orphaned data. Finally, the primary_key=True tells Django to use the relationship id (i.e., Restaurant.id) as the primary key instead of using a separate and default column id, a technique that makes it easier to track relationships.
After creating of the models, we need to migrate our project, first you need to
do migrations and after that migrate.
1 |
python manage.py makemigrations |
After doing that, you will see this output in the terminal.
1 2 3 4 |
Migrations for 'MyApp': MyApp\migrations\0005_place_restaurant.py - Create model Place - Create model Restaurant |
Now you need to migrate.
1 |
python manage.py migrate |
And this will be the output in the terminal.
1 2 3 4 5 |
Operations to perform: Apply all migrations: MyApp, admin, auth, contenttypes, sessions Running migrations: Applying MyApp.0004_auto_20200623_0836... OK Applying MyApp.0005_place_restaurant... OK |
Also we are going to create a super user, because i will show the relationship
in Django Admin Panel. so open your admin.py file in your app and register your models.
1 2 3 4 5 6 7 |
from django.contrib import admin from.models import Place, Restaurant # Register your models here. admin.site.register(Place) admin.site.register(Restaurant) |
OK now if you run your Project, and check admin panel we have our two models.
So now let’s just add some data, iam going to use Django Shell, you can use this command for opening Django Shell. make sure that you have changed your directory to your Django Project.
1 |
python manage.py shell |
Basically we are adding some Places with Restaurant.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
In [1]: from MyApp.models import Place, Restaurant In [2]: p1 = Place(name = 'abc place name', address = 'abc place address') In [3]: p2 = Place(name = 'xyz place name', address = 'xyz place address') In [4]: p1.save() In [5]: p2.save() In [6]: r = Restaurant(place = p1, serves_hot_dogs = True, serves_pizza= False) In [7]: r.save() |
Now if you check your Django Admin panel, and open your Restaurant,
you can see that we have successfully created one to one relationship.
Subscribe and Get Free Video Courses & Articles in your Email