Hello all. In this blog, I am explaining what is Many to Many Relationship and how to perform it in Django.
In my previous blog, I have explained what is Many To One relationship. Do visit.
What is a 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.
For example, let’s consider two entities, customer(person_id, person_name)
and product(product_id, 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.
Now let’s see how does the relationship works with Django. Let’s start.
- Creating a Django project and Account App
Now let’s create our Django project. The below commands create a Django project and migrate the changes to the database.
$ django-admin startproject djRelation
$ cd djRelation/
$ python3 manage.py migrate
$ python3 manage.py runserver
Once done, check if the server is working well. Then just create a Django app within our Django Project where we will be creating our model.
$ python3 manage.py startapp inventory
Once done, do all the necessary steps for registering our app to our Django project as I did below.
djRelation/settings.py
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'inventory', # add this line
]
Create a urls.py
file in our app inventory
and make sure the file should look like this.
inventory/urls.py
from django.conf.urls import url, include
from django.urls import pathurlpatterns = []
To demonstrate this example, we need no URL. We can perform it in the Django shell itself. So I am not adding any URL here. After creating this file, just map the inventory/urls.py
to the djRelation/urls.py
file.
djRelation/urls.py
from django.conf.urls import url, include
from django.urls import path
from django.contrib import adminurlpatterns = [
url(r'^admin/', admin.site.urls),
path('inventory/',include('inventory.urls')),
]
2. Creating our Accounts Model :
I am creating two models, Customer
and Product
where the primary key (id
)of the model Customer
will be a Foreign Key of Product
.
To perform Many to One relationship, we will be using the ManyToMany method in Django.
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)
Now just migrate.
$ python3 manage.py makemigrations
$ python3 manage.py migrate
3. Adding values to the Model
Let’s start our shell now. Now I am inserting some value to both tables. While inserting data to the Products
table, make sure the person field should be an instance of the Customer
table. Otherwise, it will through error.
In [1]: from inventory.models import Customer, ProductsIn [2]: c1 = Customer(cus_name="Joan Louji", cus_email="sjlouji10@gmail.com", cus_mobile="927347234")
In [3]: c1.save()In [4]: c2 = Customer(cus_name="Rion Louji", cus_email="sjlouji@gmail.com", cus_mobile="4327347234")
In [5]: c2.save()In [6]: c3 = Customer(cus_name="Louji", cus_email="joanlouji@gmail.com", cus_mobile="4323417234")
In [7]: c3.save()In [9]: p1 = Products(cus_name="Iphone", cus_qty="3")
In [10]: p1.save()In [11]: p1.cus_id.add(c1)
In [12]: p1.cus_id.add(c2)
In [13]: p1.cus_id.add(c3)
In [14]: p1.save()In [15]: cus = Customer.objects.all()In [16]: pro = Products.objects.all()In [17]: cus.values()Out[18]: <QuerySet [{'id': 1, 'cus_name': 'Joan Louji', 'cus_email': 'sjlouji10@gmail.com', 'cus_mobile': '927347234'}, {'id': 2, 'cus_name': 'Rion Louji', 'cus_email': 'sjlouji@gmail.com', 'cus_mobile': '4327347234'}, {'id': 3, 'cus_name': 'Louji', 'cus_email': 'joanlouji@gmail.com', 'cus_mobile': '4323417234'}]>In [19]: p1.cus_id.all().values()Out[20]: <QuerySet [{'id': 1, 'cus_name': 'Joan Louji', 'cus_email': 'sjlouji10@gmail.com', 'cus_mobile': '927347234'}, {'id': 2, 'cus_name': 'Rion Louji', 'cus_email': 'sjlouji@gmail.com', 'cus_mobile': '4327347234'}, {'id': 3, 'cus_name': 'Louji', 'cus_email': 'joanlouji@gmail.com', 'cus_mobile': '4323417234'}]>
In my previous blog, I have explained what is Many To One relationship. Do visit.
Feel free to contact me for any queries.
Email: sjlouji10@gmail.com
Linkedin: https://www.linkedin.com/in/sjlouji/
Complete Code can be found on my Github: https://github.com/sjlouji/Medium-Django-Model-Relationships.git
Happy coding…