Django ORM Introduction

Learn via video courses
Topics Covered

Overview

The Django web framework includes a default object-relational mapping layer (ORM) that can be used to interact with data from various relational databases such as SQLite, PostgreSQL, and MySQL. Django allows us to add, delete, modify, and query objects, using an API called ORM. ORM stands for Object Relational Mapping. An object-relational mapper provides an object-oriented layer between relational databases and object-oriented programming languages without having to write SQL queries.

Introduction to Django Admin

Django provides a default admin interface that is required to perform operations like create, read, update, and delete on the model directly. It reads a set of data that gives information about data from the model, to provide an instant interface where the user can handle the contents of the application. The admin app is activated by default and already added into the INSTALLED_APPS present in the settings.py file. ‘localhost:8000/admin/’ is used to access the admin interface in the browser. It then asks the user to log in, if no log-in ID is created the following command will create a new superuser:

After creating the superuser, we start the server using the command:

Open the URL ‘localhost:8000/admin/’ in the browser again, enter your username and password then log in. A Django Admin Dashboard opens where we can add, remove and update data belonging to any registered model.

How the ORM works?

In the following section, we will see how ORM works. We will be using the following Django Models for demonstration:

In the above code, we created two models Album and Song. Whenever an instance of a model is created in Django, it will display the object as Modelname Object(1) in the admin interface. Hence to change the display name we use the function def __str__(self). The Strfunction in a Django model returns a string that is rendered as the display name of instances for that model. In our case, it will display the name of the title for the Model Album and the name of the song for the Model Song. In the Model Song, we are linking the second field, album with the Model Album. Register the model in the admin.py file,

After creating and registering the models, we need to use the following command:

In the above commands, makemigrations is responsible for packing up the changes into individual migration files, and migrate is responsible for applying those to our database.

Now we need to access Django ORM, it can be accessed by using the following command inside our project directory:

This leads us to an interactive Python console. Next, we are supposed to import our models using the following command:

After this, we can perform ORM operations.

Django ORM- Inserting, Updating, and Deleting Data

Django lets us interact with its database models using an API called ORM. In this section, we will discuss some useful operations like adding, updating, and deleting data using Django ORM.

  • Adding Objects

We write the following code to create and save an object of Model Album:

We write the following code to create and save an object of Model Song:

  • Retrieving objects

Retrieving stands for getting the result of the search we make. So for retrieving the data in Django, let us add some records for ease of explanation.

To retrieve all the objects of a model,all()is used:

The output is a set of objects that match the query. Since we used the __str__() function for the model Album we see the output has a title displayed for all the objects.

  1. The filter() is used to retrieve the data that exists already based on the condition we give in the command. For example, in the code below we used to filter(artist="The Beatles") so the query set returned shows the list of albums with the artist name as "The Beatles".
  1. The exclude()is used to retrieve the objects excluding or omitting the conditions we give in the command. In the code below we used, exclude(artist= "The Beatles") and the output it returns does not contain any album with the artist name as "The Beatles".
  1. Theget()is used to retrieve a single object matching the conditions we give in the command. In the code below, we used get(pk = 3), pk stands for the primary key. It uniquely identifies each row in the table. So here pk=3 returns the third object of the model. Django documentation declares that the primary key can be accessed using the keyword pk.
  • Modifying existing objects

Django also allows us to modify existing objects. At first, we use get() to retrieve the single object which we want to modify then enter the data as in the code below a.artist="One Direction"and save it using a.save().

  • Deleting Objects

To delete a single object, at first we use the get() function and then delete():

To delete multiple objects, we can use filter() or exclude():

What is a QuerySet?

A Query Set is a collection of data from a database. Query set allows us to get data easily, by allowing us to filter, create, order, etc. Let us take an example of a database table named Students.

IDNameSubjects
01ThomasPhysics
02JerryMathematics
03JacobBiology
04RobertComputer Science
05BetsyChemistry

In views.py, we have a view called testing where we will test different queries. In the source code below, we use the all()to get all the records and fields of the model Students. The object is placed in a variable known as mydata, it is sent to the template through the context object as mystudents:

Model Students contain 5 records, they are listed inside the Query Set as 5 objects.

Below is the source code of template.html, where we will be using mystudents object to generate content:

The output of the template.html is:

  • Django Shell

So to enter into the Django shell, the following command should be entered into the command prompt in the virtual environment:

This will lead us to an interactive console.

  • All objects

There are some methods to get data from a model into a queryset:

1. all() It returns each object as a Python dictionary with names and values as key and value pairs respectively. The source code for the same is given below:

The output is:

2. values_list() The values_list() returns only the column that is specified. The source code for the same is given below:

The output is:

  • Create Objects

To create an object, at first we need to import the Students

Thus for creating an object, use the following code

  • Filter Objects

The filter() returns a filtered search. The source code for the same is given below:

The output is:

Django also allows fetching filtered data based on multiple conditions, like AND and OR operations, and also be performed.

1. AND We can get filtered data satisfying both of the queries mentioned. Refer to the example for demonstration.

The output it returns:

2. OR We can also get filtered data that matches either of the query mentioned. An example is mentioned below.

The output it returns:

3. Field Lookups Field lookups are keywords that represent specific SQL keywords.

The output it returns:

Some of the field lookup keywords are mentioned below:

KeywordsDescription
ContainsContains the phrase
icontainsContains the phrase but case sensitive
endswithEnds with
iendswithEnds with but case sensitive
startswithStarts with
istartswithStarts with but case sensitive
  • Ordering objects

Django provides a feature to sort the query sets, using order_by().

1. To sort the result alphabetically by name

It returns the following:

2. To sort in descending order The results are by default sorted in ascending order. To sort in descending order, we insert a '-' minus sign in front of the field name. Thus for sorting in reverse alphabetical order we add '-' in front of 'name'.

The above code returns:

3. Multiple Order by To order based on more than one field, kindly consider the code below.

The above code returns:

  • Complex queries through method-chaining

A query set can be combined with another query set by chaining them together,

The above code would return

Conclusion

Hello Developer! Well after going through this article you must have understood what ORM is. Let us summarize what we learned from this article

  • ORM allows us to interact with data from various relational databases such as SQLite, PostgreSQL, and MySQL.
  • ORM stands for Object Relational Mapping.
  • Django allows us to add, delete, modify and query objects, using an API called ORM.
  • Django provides a default admin interface that is required to perform operations like create, read, update and delete on the model directly.
  • ‘localhost:8000/admin/’ is used to access the admin interface in the browser. 8000 is the default port. We can also change the port to our desired one if we are running multiple applications at the same time.
  • A Query Set is a collection of data from a database.
  • Query set allows us to get data easily, by allowing us to filter, create, order, etc.