Hello all. In this blog, I am explaining what is Many to One Relationship and how to perform it in Django.
In my previous blog, I have explained what is One To One relationship. Do visit.
What is a Many To One Relationship?
A Many to One relationship is a type of relationship where the first model can have one or many records in the second table and the second table can be related only to one record in the first table. This is one of the most commonly used relationships in the industry.
For example, let’s consider two entities person(person_id, person_name)
and account(account_id, amount)
. Here each person can hold more than one account, whereas an account can be related to only one person.
A Many to One relationship is like a relationship between you and your parents. Your parents can have any number of children where you can have only one parent.
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 account
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',
'account', # add this line
]
Create a urls.py
file in our app account
and make sure the file should look like this.
account/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 account/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('account/',include('account.urls')),
]
2. Creating our Accounts Model :
I am creating two models, Person
and Account
where the primary key (id
)of the model Person
will be a Foreign Key of Account
.
To perform Many to One relationship, we will be using the Foreign Key method in Django.
account/models.py
from django.db import models# Create your models here.
class Person(models.Model):
name = models.TextField(max_length=100)
email = models.EmailField()
mobile = models.TextField(max_length=100)class Account(models.Model):
person = models.ForeignKey("Person",on_delete=models.CASCADE)
account_number = models.TextField()
balance = 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 Account
table, make sure the person field should be an instance of thePerson
table. Otherwise, it will through error.
In [1]: from account.models import PersonIn [2]: p1 = Person(name="Joan louji", email="sjlouji10@gmail.com", mobile="123412")
In [3]: p1.save()In [4]: p2 = Person(name="Rion", email="rion@gmail.com", mobile="0987632")
In [5]: p2.save()In [6]: from account.models import AccountIn [7]: a1 = Account(person=p1, balance="1002335", account_number="432198176354")
In [8]: a1.save()In [9]: a2 = Account(person=p1, balance="1002", account_number="4321981763541234")
In [10]: a2.save()In [11]: a3 = Account(person=p1, balance="103412", account_number="43219813254")
In [12]: a3.save()In [13]: p = Person.objects.all()
In [14]: p.values()Out[15]: <QuerySet [{'id': 1, 'name': 'Joan louji', 'email': 'sjlouji10@gmail.com', 'mobile': '123412'}, {'id': 2, 'name': 'Rion', 'email': 'rion@gmail.com', 'mobile': '0987632'}]>In [16]: a = Account.objects.all()
In [17]: a.values()Out[18]: <QuerySet [{'id': 1, 'person_id': 1, 'account_number': '432198176354', 'balance': '1002335'}, {'id': 2, 'person_id': 1, 'account_number': '4321981763541234', 'balance': '1002'}, {'id': 3, 'person_id': 1, 'account_number': '43219813254', 'balance': '103412'}]>
In my previous blog, I have explained what is One To One relationship. Do visit.
In my next blog, I am explaining how to perform many-to-may relationships with Django. Stay connected.
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…