Django Python One to One Relationship Example

Published On: 29/06/2022 | Category: Django Python

Hi Dev,

If you need to see example of django one to one relationship example. it's simple example of django one to one example. I would like to show you django models with relationships one to one relationship. I explained simply step by step django one to one relationship example database.

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

Here i explained simply step by step django one to one relationship example database:

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 manage.py startapp place

Next, you need to add it in the settings.py file as follows:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'place',
]
Step 3 : Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 4: Create a Model

In this step we will require the database model for storing contacts.Open the place/models.py file and add the following code:

place/models.py
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 "%s the place" % 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 "%s the restaurant" % self.place.name

After creating these model, you need to create migrations using the following command:

Step 5 : Create a Migrations
python manage.py makemigrations

After successfully run the above command go to the place/migrations/0001_initial.py

place/migrations/0001_initial.py
# Generated by Django 4.0.5 on 2022-06-28 12:18

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Place',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=50)),
                ('address', models.CharField(max_length=80)),
            ],
        ),
        migrations.CreateModel(
            name='Restaurant',
            fields=[
                ('place', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='blog.place')),
                ('serves_hot_dogs', models.BooleanField(default=False)),
                ('serves_pizza', models.BooleanField(default=False)),
            ],
        ),
    ]

Next, you need to migrate your database using the following command:

python manage.py migrate
Step 6 : Adding values to the Model

So, in this step let’s start our shell now. now i am inserting some value to both tables. While inserting data to the Restaurant table, make sure the Place field should be an instance of Place table. Otherwise, it will through error.

python manage.py shell
In [1]: from blog.models import Place

In [2]: p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
In [3]: p1.save()

In [4]: p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
In [5]: p2.save()

In [6]: from blog.models import Restaurant

In [7]: r1 = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
In [8]: r1.save()

In [9]: r2 = Restaurant(place=p2, serves_hot_dogs=False, serves_pizza=True)
In [10]: r2.save()

In [11]: p = Place.objects.all()
In [12]: print(p)

<QuerySet [<Place: Demon Dogs the place>, <Place: Ace Hardware the place>]>

In [13]: r = Restaurant.objects.all()
In [14]: print(r)

<QuerySet [<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>]>

In [15]: r.values()

Out[16]: <QuerySet [{'place_id': 1, 'serves_hot_dogs': True, 'serves_pizza': False}, {'place_id': 2, 'serves_hot_dogs': False, 'serves_pizza': True}]>

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

This will through Integrity Error.

In [17]: r3 = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)

In [18]: r3.save()

IntegrityError: UNIQUE constraint failed: place_restaurant.place_id

I Hope It will help you....