Django Python One To Many Relationship Example

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

Hi Dev,

Now, let's see post of django python one to many relationship example. I would like to share with you django python one to many relationship example database. Here you will learn django python one to many relationship example python. this example will help you django python one to many relationship example query.

A one record in a table can be associated with one or more records in another table. suppose a car company can have one or more car model and car model can only belong to one car company.

Here i explained simply step by step django one to many 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 company

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',
    'company',
]
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 company/models.py file and add the following code:

company/models.py
from django.db import models


class Car(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name


class CarModel(models.Model):
    name = models.CharField(max_length=255)
    car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True)
    
    def __str__(self):
        return self.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 company/migrations/0001_initial.py

company/migrations/0001_initial.py
# Generated by Django 4.0.5 on 2022-06-29 05:35

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


class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0002_multipleimage'),
    ]

    operations = [
        migrations.CreateModel(
            name='Car',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=255)),
            ],
        ),
        migrations.CreateModel(
            name='CarModel',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=255)),
                ('car', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='blog.car')),
            ],
        ),
    ]

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 CarModel table, make sure the Car field should be an instance of Car table. Otherwise, it will through error.

python manage.py shell
In [1]: from company.models import Car, CarModel

In [2]: mercedes = Car.objects.create(name="Mercedes")
In [3]: bmw = Car.objects.create(name="BMW")

In [4]: Car.objects.all()

<QuerySet [
    <Car: Mercedes>, 
    <Car: BMW>
]>

creating a new car model:

In [5]: c180 = CarModel.objects.create(name=”C180", car=mercedes)

In [6]: c180.car

<Car: Mercedes>

In [7]: c180.car.name

'Mercedes'

Create relation between Model and Car.

In [8]: c200 = CarModel.objects.create(name=”C200")
In [9]: c200.car = mercedes
In [10]: c200.save()

In [11]: c200.car.name

'Mercedes'

Create relation between Car and Model.

In [12]: x1 = CarModel.objects.create(name=”X1")
In [13]: x3 = CarModel.objects.create(name=”X3")

In [14]: CarModel.objects.all()

<QuerySet [
    <CarModel: X1>, 
    <CarModel: X3>
]>

In [15]: bmw.carmodel_set.add(x1, x3)

In [16]: bmw.carmodel_set.all()

<QuerySet [
    <CarModel: X1>, 
    <CarModel: X3>
]>

Retrieve Records :

From car to car model:

In [17]: mercedes.carmodel_set.all()

<QuerySet [
    <CarModel: C180>, 
    <CarModel: C200>
]>

In [18]: mercedes.carmodel_set.first()

<CarModel: C180>

In [19]: mercedes.carmodel_set.first().name

'C180'
Step 7 : Reverse Relationship :

In this step add a related_name will be the attribute of the related object that allows you to go ‘backwards’ to the model with the foreign key on it.

class CarModel(models.Model):
    name = models.CharField(max_length=255)
    car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True, related_name='models')

    def __str__(self):
        return self.name

You can access the “CarModel” instances that are related to your “Car“ instance by going car_instance.models.all(). You can no longer use carmodel_set.

In [20]: x5 = CarModel.objects.create(name=”X5")
In [21]: x6 = CarModel.objects.create(name=”X6")


In [22]: bmw.models.add(x5, x6)

So, related_query_name is for use in Django querysets. It allows you to filter on the reverse relationship of a foreign key related field.

class CarModel(models.Model):
    name = models.CharField(max_length=255)
    car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True, related_name='models', related_query_name='model')

    def __str__(self):
        return self.name
In [23]: Car.objects.filter(model__name="C180")

<QuerySet [
    <Car: Mercedes>
]>

When we try to assign the same model to one more than cars :

In [24]: bmw.models.all()

<QuerySet [
    <CarModel: X1>, 
    <CarModel: X3>, 
    <CarModel: X5>, 
    <CarModel: X6>
]>

In [25]: mercedes.models.add(x1)

In [26]: mercedes.models.all()

<QuerySet [
    <CarModel: C180>, 
    <CarModel: C200>, 
    <CarModel: X1>
]>

In [27]: bmw.models.all()

<QuerySet [
    <CarModel: X3>, 
    <CarModel: X5>, 
    <CarModel: X6>
]>

In [28]: bmw.models.add(x1)

<QuerySet [
    <CarModel: X1>, 
    <CarModel: X3>, 
    <CarModel: X5>, 
    <CarModel: X6>
]>

In [29]: mercedes.models.all()

<QuerySet [
    <CarModel: C180>, 
    <CarModel: C200>, 
]>

I Hope It will help you....