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 startapp place

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

Step 3 : Database Setup

Next step, we will modify the file and update the database settings to configure the mydb database:
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
Step 4: Create a Model

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

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" %

class Restaurant(models.Model):
    place = models.OneToOneField(
    serves_hot_dogs = models.BooleanField(default=False)
    serves_pizza = models.BooleanField(default=False)

    def __str__(self):
        return "%s the restaurant" %

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

Step 5 : Create a Migrations
python makemigrations

After successfully run the above command go to the place/migrations/

# 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 = [
                ('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)),
                ('place', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='')),
                ('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 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 shell
In [1]: from blog.models import Place

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

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

In [6]: from blog.models import Restaurant

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

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

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]:

IntegrityError: UNIQUE constraint failed: place_restaurant.place_id

I Hope It will help you....