Django Python Many To Many Relationship Example

Published On: 01/07/2022 | Category: Django Python

Hi Dev,

Hello all! In this article, we will talk about django python many to many relationship example. I would like to share with you django python many to many relationship example database. This tutorial will give you simple example of django python many to many relationship example python. This article will give you simple example of django python many to many relationship example query.

So, many to many relationship in this type of relationship, each record of the first table is related to many records of the second table and also each record of the second table is related to many records of the first table.

Suppose i have two table one is Customer and second is Product. inside Customer table in which field customer_id and customer_name, next Product table field product_id and product_name. In this case, each customer can be related to n number of products and each product can be linked to n number of customers.

Here Now let’s see how does the relationship works with Django. Let’s start:

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 inventory

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

inventory/models.py
from django.db import models

# Create your models here.
class Customer(models.Model):
    cus_name = models.TextField(max_length=100)
    cus_email = models.EmailField()
    cus_mobile = models.TextField(max_length=100)
    
class Products(models.Model):
    cus_id = models.ManyToManyField("Customer")
    cus_name = models.TextField()
    cus_qty = models.TextField(max_length=100)

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 inventory/migrations/0001_initial.py

inventory/migrations/0001_initial.py
# Generated by Django 4.0.5 on 2022-06-30 06:38

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Customer',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('cus_name', models.TextField(max_length=100)),
                ('cus_email', models.EmailField(max_length=254)),
                ('cus_mobile', models.TextField(max_length=100)),
            ],
        ),
        migrations.CreateModel(
            name='Products',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('cus_name', models.TextField()),
                ('cus_qty', models.TextField(max_length=100)),
                ('cus_id', models.ManyToManyField(to='inventory.customer')),
            ],
        ),
    ]

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

creating a new Customer model:


In [1]: from inventory.models import Customer, Products

In [2]: c1 = Customer(cus_name="Bhavesh Sonagra", cus_email="[email protected]", cus_mobile="7600322437")
In [3]: c1.save()

In [4]: c2 = Customer(cus_name="Vishal Patel", cus_email="[email protected]", cus_mobile="4327347234")
In [5]: c2.save()

In [6]: c2 = c3 = Customer(cus_name="Nikhil Patel", cus_email="[email protected]", cus_mobile="4565417234")
In [7]: c3.save()

creating a new products model:

In [8]: p1 = Products(cus_name="IPhone 13 Pro", cus_qty="99")
In [9]: p1.save()

In [10]: p1.cus_id.add(c1)
In [11]: p1.cus_id.add(c2)
In [12]: p1.cus_id.add(c3)
In [13]: p1.save()

Get customer and product object.

In [14]: cus = Customer.objects.all()

In [15]: pro = Products.objects.all()

In [16]: cus.values()

Out[17]: <QuerySet [{'id': 1, 'cus_name': 'Bhavesh Sonagra', 'cus_email': '[email protected]', 'cus_mobile': '7600322437'}, {'id': 2, 'cus_name': 'Vishal Patel', 'cus_email': '[email protected]', 'cus_mobile': '4327347234'}, {'id': 3, 'cus_name': 'Nikhil Patel', 'cus_email': '[email protected]', 'cus_mobile': '4565417234'}]>

In [18]: p1.cus_id.all().values()

Out[19]: <QuerySet [{'id': 1, 'cus_name': 'Bhavesh Sonagra', 'cus_email': '[email protected]', 'cus_mobile': '7600322437'}, {'id': 2, 'cus_name': 'Vishal Patel', 'cus_email': '[email protected]', 'cus_mobile': '4327347234'}, {'id': 3, 'cus_name': 'Nikhil Patel', 'cus_email': '[email protected]', 'cus_mobile': '4565417234'}]>

I Hope It will help you....