Blog

Django Model Relationship and its Types | Django Tutorials

Django Model relationship and its types copy
Django

Django Model Relationship and its Types | Django Tutorials

Django Model Relationship and its Types

Today’s tutorial is very important because, without the Django Model relationship, we cannot develop a good website or application. The model relationship is the way used to combine two models to each other if they have any relationship. You know, in the school environment, teacher and student have a relationship, doctor and patient have a relationship, buyer and product have a relationship, etc. So, more about Model relationships, you will learn in this tutorial, if you read from start to end.!

What is Django Model?

Actually Django model is the database table in which data is stored, retrieved, search. update and delete. Model is referred to a table that is a collection of rows and columns. In Django, we can create a model for a specific entity, each model has different types of fields as text type, password type, email type, URL type, number type, image type, etc. We can add different types of fields as well as different behaviors also in the model. To create a model we need to create a model class in which we mentioned fields and behavior according to our needs.

from django.db import models

class Student(models.Model):
       full_name = models.CharField(max_length=30)
       nick_name = models.CharField(max_length=30)

What is Model Relationship?

Actually, there are objects which have a relationship to each other. For example, childer have a relationship with their parents. Teachers have relationships with students etc. So in the database environment, we have to define a relationship between models, have you understand? If not, read continue!

What is an entity? The entity is the real word idea, for example, any things, person, place, etc are all entities. Person, laptop, tablet, mobile, London, Car is the example of entities. Another thing is that each entity has attributes, attributes are characteristics or properties of the entity. As mobile is the entity and mobile name, model number, color, size, weight, etc are the attributes of mobile. So to store the properties of mobile phones in a database we have to create a model class.

from django.db import models

class Mobile(models.Model):
       name = models.CharField(max_length=30)
       model_number = models.CharField(max_length=30)

……….

So, now understand what is relationship. Now we will analyze what is an object on which mobile is depending and have also more attributes. We know that customers buy the mobile, we will add a column in the mobile model with the name of the buyer. The buyer will be a customer and will have attributes like name, email, address, etc. So we will create another model with the name of the buyer but in the mobile model, we will add a column giving a reference for the buyer model using a foreign key, for example.

buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE) # we need to add this line of code to mobile model.

The buyer will be another table which we will mention.

Such a relationship is called a model relationship.

Need of Creating Relationship between Models

There are different reasons, due to that we create a model relationship in the database. The most important reason is we want to remove the complexity of the tables. Because when we add all the data in one table, then it will become difficult to retrieve, update, delete the data.

Normalization is a technique used to remove repeating groups and the complexity of database tables. In the normalization technique, we divide one table into distinct tables, then distinct tables are linked to each other using the model relationship technique.

So, if we mentioned in points, why need to create a model relationship, we can understand better:

  • To create a database in a simple way
  • To remove complexities
  • Easy to view data
  • Easy to perform CRUD operations on models

How to create Django Model Relationship

There are different types of Django Model relationships as mentioned following:

  • One to Many 
  • One to One 
  • Many to Many

We will share an example for each type for your understanding. As more examples and explanations we will add from time to time as we update this tutorial.

The following Django model is linked with User model with One to One relatiosnhp, which means for eah user instane there will be only one profiel instance. One user cannot have two profiel accoridng to rule of relationship.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to=’profile_pic’)
    address = models.CharField(max_length=300, default=”None”)
The following model class is about blog posts which linked to the User model class with a Foreign key. To adding a Foreign key, we mean to make one to many relationships. One to many relationships means, one user can post many posts. One instance of the user has many posts. But one post instance can be published by only ONE user.
class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to=’post_pic’)
    title= models.CharField(max_length=100, default=”None”)
    description= models.TextField(max_length=500, default=”None”)
The following model calss have many to many relatipship with Post, which means, one post instance can have many category and one instance of cateogry can have many post. For exmapel computer related post may categoriezed in IT, Technology, Computer etc.
class Category(models.Model):
    user = models.ManyToManyField(Post, on_delete=models.CASCADE)
    name= models.CharField(max_length=100, default=”None”)

Now! what you have to do?

As you have understood this article about “Django Model Relationship”, now you must follow instructions as discussed in this article. In case of any issues or problems, don’t worry, you can discuss them with us.

On other hand, If you have any suggestions or knowledge about this article, you can share it with us, we will appreciate you!

If this article is good then share it on FacebookTwitterPinterestInstagram, etc.

Advanced Tutorials for Beginners

Django File Uploading | Django Tutorial for Beginners

What is Django Cache | Django Tutorial for Beginners

What is Django Model Manager | Django Tutorials

Can Web Design using Python Programming?

Top 20 Python Real World Applications | Python tutorials

Leave your thought here

Your email address will not be published.

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
  • Attributes
  • Custom attributes
  • Custom fields
Click outside to hide the compare bar
Compare
Wishlist 0
Open wishlist page Continue shopping