Django ORM Tutorial – The concept to master Django framework

Django ORM has been mentioned in all of the database & model tutorials. It is an amazing implementation to increase development speed. Yes, there are other ORMs and some people don’t even like ORMs. No worries!! If you didn’t understand what an ORM is. We will cover that in this tutorial.

The other important topic is of Querysets. These are an important part of ORMs in general. We have used Querysets many times in our tutorials. In this Django ORM tutorial, Querysets are also explained from the very basics. Let’s get started.

1. ORMs

  • What is an ORM?
  • The Problem Solved by an ORM
  • Django ORM

2. Querysets in Django

3. Different Relationships between Fields

  • One to One Relationship
  • One to Many Relationships
  • Many to Many Relationships

4. Conclusion

  • The Problems with Django ORM

Keeping you updated with latest technology trends, Join DataFlair on Telegram

Django ORM Tutorial

1. What is an ORM?

ORM is an acronym for the object-relational mapper. The ORM’s main goal is to transmit data between a relational database and application model. The ORM automates this transmission, such that the developer need not write any SQL.

ORM, as from the name, maps objects attributes to respective table fields. It can also retrieve data in that manner.

This makes the whole development process fast and error-free.

Django ORM Tutorial

In the above image, we have some Python objects and a table with corresponding fields. The object’s attributes are stored in corresponding fields automatically. An ORM will automatically create and store your object data in the database. You don’t have to write any SQL for the same.

The Problem Solved by ORM

ORMs have certain benefits over the traditional approach. The main advantage ORMs provide is rapid development. ORMs make project more portable. It is easier to change the database if we use ORMs.

django ORM vs SQL

In the past, web developers needed to have knowledge of databases too. A database has been an important component from the start. The programming languages used for web development use classes and object for data-interpretation. The class is used to a defined data structure in web-applications. Then the same database schema is created in the database. This task requires skill and knowledge of SQL.

Knowing SQL is also not enough since SQL implementations slightly differ from one another in different databases. This became a difficult and time-consuming task. So, to resolve this, the concept of ORM was introduced in web frameworks. ORMs automatically create a database schema from defined classes/ models. They generate SQL from Python code for a particular database. ORMs let the developer build the project in one language that means Python.

This increased the popularity of ORMs and web-frameworks. There are different ORMs available in the market but one of the best is Django ORM.

different orm connectors - Python Django ORM

Not only ORMs, but there are also multiple Python Connectors for databases available. These ORMs use connectors to connect databases with a web application. you have to install the connector of a specific database you want to work with. We will be working with MySQL databases.

Introduction to Django ORM

Django is shipped with its own ORM. It is a very efficient ORM and is tightly coupled with the Django framework. Django ORM is suitable for handling low-medium complexity queries. Although, some consider SQLAlchemy ORM to be a better option. The migrations feature by Django is also a part of Django ORM. The ORM has many benefits engulfing those of migrations and Querysets. Django is the only framework which is complete in itself.

Is it necessary to use ORM?

This is totally a developer’s choice. Although there are certain benefits of ORM, there are some downsides too. It is beneficial for developers as it allows faster development. Sometimes ORMs generate more complex queries then they should. This can result in a performance decrease. Therefore, it is totally the developer’s choice and the level of work they are doing. For example – Django ORM is efficient for working with low-medium complexity models.

Django ORM vs SQLAlchemy?

In most cases, people prefer SQLAlchemy over Django ORM. The reason being SQLAlchemy is more adept to work with high-complexity data structures. Django ORM is powerful in its own way. The ORM provides features integrated with Django which are more important than just performance improvement.

Currently, Django ORM is not swappable with SQLAlchemy. There are some hacks to do it but it’s unofficial. Django’s future releases are expected to provide this functionality. Also, both SQLAlchemy and Django ORM is actively developed.

So, there is no clear winner and it totally depends on the type of project you are working on.

2. Querysets in Django

We all use queries to retrieve data from the database. Querysets are Django’s way to retrieve data from the database. The Django ORM lets us use Querysets.

A Queryset is a list of objects of a model. We use Querysets to filter and arrange our data. These make our work as a Python developer easier.

We will be practicing different implementations of Querysets. We have discussed most of them in our previous articles. So, you can check them out from DataFlair’s Django Tutorial Series. Querysets are generally associated with CRUD applications. We will be discussing that in a separate tutorial.

In this tutorial, we will be focusing more on Django ORM.

Different Relationships between Fields

Django ORM provides a level of abstraction which makes it easy to work with objects. ORM will automatically relate the object’s attributes to corresponding table fields. We are going to make some models and check their field relationships in other tables.

It is expected that you can make models and applications. This Django ORM tutorial is an advanced concept and basics of Django is a prerequisite.

Now, you can create models by pasting the code in models.py of your application. Let’s get started.

1. One to One Relationship

A one-to-one relationship exists between two tables. For each row in table1, there shall be a row/ entity in table2.

Let’s understand it with an example.

one to one relationship - Django ORM

There are two tables here, Customer and Vehicle. Every customer owns only one vehicle. Thus, a one-to-one relationship exists. Now, paste this code in models.py to implement this.

Code:

from django.db import models

#DataFlair #DjangoTutorials
# Create your models here.
class Customer(models.Model):
    name = models.CharField(max_length=255)

class Vehicle(models.Model):
    name = models.CharField(max_length=255)
    customer = models.OneToOneField(
        Customer,
        on_delete=models.CASCADE,
        related_name='vehicle'
    )

Code Display:

One to One Relationship Model Code

Now, we will register these models with admin to populate them.

register models with admin - Django ORM

Now, create some objects from the Django Admin. First, make some owner objects. It will show a dropdown list of Customer objects in Vehicle.

Dropdown list of Customer objects in Vehicles

Now, after adding some objects we will check the database.

Customer Table - Django ORM Tutorial

Customer Table

Vehicle Table - Django ORM

Vehicle Table

Now, just focus on Vehicle Table. You can see that it stores the Customer ID which is the same field as ID in the Customer table. This is a one-to-one relationship. Let’s see the SQL we would have to write for the same task.

Complex SQL Terminal Code - Django ORM Tutorial

That is some complex SQL. Django ORM saves us a lot from writing this code and syncing our models. Check out the DataFlair’s Django Migrations Tutorial.

2. One to Many Relationships

Just like one to one we can have one-to-many relationships. We are going to use a different model for showcasing this.

A one to many relationships is where one object from table1 can have multiple relations with entities in table2. Although, table2 objects will have only one relation to the object of table1.

Let’s understand this from the example:

one to many relationship - Django ORM

Before developing this model: please make it in a new application.

The code for this model is:

from django.db import models

#DataFlair #DjangoTutorials
# Create your models here.
class Customer(models.Model):
    name = models.CharField(max_length=255)

class Vehicle(models.Model):
    name = models.CharField(max_length=255)
    customer = models.ForeignKey(
        Customer,
        on_delete=models.CASCADE,
        related_name='Vehicle'
    )

Code Display:

One to Many relationship code - Django ORM tutorial

Populate the models via admin. Once you have created some objects then check the database.

Customer Table - Django ORM

Customer Table

Vehicle Table - Django ORM

Vehicle Table

From this table, we can see that one customer can have more than one vehicle.

3. Many to Many Relationships

We can also implement many to many relations in the database. In this case, we are taking examples of multiple drivers.

many to many relationship - Django ORM tutorial

Here we have multiple workers for multiple machines. A worker can be assigned to operate more than one machine. Also, a machine can be operated by multiple workers one at a time.

To implement the same in model, paste this code in models.py:

from django.db import models

# Create your models here.
#DataFlair #Many to Many Relationship
class Worker(models.Model):
    name = models.CharField(max_length=255)

class Machine(models.Model):
    name = models.CharField(max_length=255)
    worker = models.ManyToManyField(
        Worker,
        related_name='Machine'
    )

Code Display:

Many to many relationship code - Django ORM Tutorial

Now, let’s fill some data in them again. We will now inspect the database.

Worker Table

Worker Table

Machine Table

Machine Table

Many to many relationship table - Django ORM Tutorial

Many to many relationship table

This is a special case of relationships. Many to Many Relationship requires a separate table. There they store objects related to other objects.

These relationships are common for objects and classes. These can be difficult to write with SQL.

Summary

Django ORM and other ORMs are very powerful tools for web-developers. However, there are some issues which cannot be solved by them. ORMs are abstractions and automate a process. There are points where they can generate more complex queries than manual.

It all depends on the developer and their skill with the corresponding database. On the contrary, the ORM exists only for SQL and RDBMS (Relational database management systems). There are no ORMs for NoSQL databases. So, it depends on your use case and how you perceive the data.

ORMs have both bad and good sides. Particularly Django ORM is highly favored by web-developers. It’s not very efficient when compared to SQLAlchemy. The deep integration with the Django framework is where it really shines. Also, Django ORM is an abstraction layer. It provides us with features like Querysets and migrations and these relations.

Now, let’s move on to the next article – Django CMS

Share your thoughts and queries regarding the Django ORM tutorial in the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.