Django CRUD on objects

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, it allows us to perform CRUD operations which stands for create, retrieve, update, and delete on our database model.

Introduction

Django allows us to create database models and interact with them using an API called ORM. The primary goal of ORM is to send data between a database and application models. It represents a relationship between a database and a model. The main advantage of using Django ORM queries is that it speeds up and eliminates errors by providing the user to perform certain operations(add, retrieve, update, and delete) on the database table. It allows us to perform CRUD operations which stands for create, retrieve, update, and delete on our database model.

CRUD Explanation

CRUD operations include creating, retrieving, updating, and deleting data from the database model we create in Django. It helps us to keep a track of our data as well as to modify it. Let us consider an example. We created two models albums and song.

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 Str function 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, an 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 CRUD operations.

Create View

We can create and add new records in the database table. Therefore, the following code is used to create and save an object in Model Album:

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

Retrieve View

Retrieving stands for getting the result of the search we make. This operation allows the user to get the list of all the records we entered. 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 the 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 "The Beatles".
  1. The get() 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=3pk=3 returns the third object of the model. Django documentation declares that the primary key can be accessed using the keyword pk.

Detail View

A detail View is a view (logic) that allows a particular instance or a particular record of a table from the database to be displayed. For a detailed view, we need a primary key which is the id for the identification of a particular instance of the model. Let us create a view in the views.py file.

In the above code,

  • We have imported the model we created.
  • We have created a class detailview.
  • We have passed the request and id for the unique identification of a particular instance of the model.
  • We have created a dictionary context, for data with field names as keys.
  • We link the HTML page we will create and the dictionary context under the return render.

Now we are supposed to link the view to the URL path in the urls.py file,

In the above code,

  • We have imported the detailview.
  • In the URL path, we link the detailview and the id for each instance of a table.

We create a template named detailview.html in the folder template.

Update View

Django also allows us to modify existing objects. This is an updated operation of CRUD. At first, we use the 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().

Delete View

This is the delete operation of CRUD. 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():

Conclusion

Hello developer!! I am sure by now you must have understood what Django CRUD on objects is. Let us summarize what we have learned so far

  • Django allows us to add, delete, modify, and query objects, using an API called ORM.
  • CRUD operations include creating, retrieving, updating, and deleting data from the database model we create in Django.
  • Create view is used to create and add new records in the database table.
  • The retrieve view is used for getting the result of the search we make.
  • Detail View is a view (logic) that allows a particular instance of a table from the database to be displayed with other details.
  • The update view allows us to modify existing objects.
  • Delete view helps us in deleting a record.