Update, Insert and Delete Data with Django ORM- Scaler Topics (2024)

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. ANDWe can get filtered data satisfying both of the queries mentioned. Refer to the example for demonstration.

The output it returns:

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

The output it returns:

3. Field LookupsField 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 orderThe 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 byTo 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.
Update, Insert and Delete Data with Django ORM- Scaler Topics (2024)

FAQs

How to insert, delete, and update in Django model? ›

To delete a record from the Employee table using Django's ORM, you can follow these steps:
  1. Retrieve the record you want to delete.
  2. Call the delete() method on the retrieved record.

How do I update in ORM? ›

Updating ORM Objects using the Unit of Work pattern

The primary way is that it is emitted automatically as part of the unit of work process used by the Session , where an UPDATE statement is emitted on a per-primary key basis corresponding to individual objects that have changes on them.

How to update data from database in Django? ›

The following are the steps to update data in a database using Django:
  1. Create a model class for your database tables.
  2. Define the fields of the model class with their respective types.
  3. Create your table in the database by running python manage.py sqlmigrate my_table .

What is the ORM method in Django? ›

The Object-Relational Mapper (ORM) is one of Django's most powerful features, allowing you to interact with your database in the same way that you would with SQL. In truth, Django's ORM is essentially a pythonic technique to build SQL to query and edit your database and obtain results.

How do I update a value in Django? ›

To update a record, we need the ID of the record, and we need a template with an interface that let us change the values. First we need to make some changes in the index. html template.

How to edit and delete in Django? ›

Django Delete Data
  1. Django Delete Data. ❮ Previous Next ❯ ...
  2. >>> from members.models import Member. >>> x = Member.objects.all()[5] ...
  3. >>> x.firstname. This should give you this result:
  4. 'Jane' Now we can delete the record:
  5. >>> x.delete() The result will be:
  6. (1, {'members.Member': 1}) ...
  7. >>> Member.objects.all().values()

What is the difference between Django ORM and SQLAlchemy? ›

Differences – SQL Alchemy vs Django

Main difference is that Django ORM uses the “active record implementation”, and SQL Alchemy uses “data mapper implementation”. It means that Django ORM cannot use our models for queries if every row is not linked with the overall model object.

What is the difference between write and update? ›

in write method , all the record has been updated of model and in update method, only particular filed of record you can update. This is the main difference between write and update method.

How to update value in QuerySet Django? ›

The update() method is applied instantly, and the only restriction on the QuerySet that is updated is that it can only update columns in the model's main table, not on related models. You can't do this, for example: >>> Entry. objects.

What is the difference between save and update in Django? ›

When to use update. you are updating fields of one or many records (note: update cannot be used to create a new record, like save can). you don't need to re-use a model instance after updating. you don't need your overridden save() method or any pre_save or post_save signals to run.

How to update date automatically after a value change in Django? ›

You want to add the auto_now field and set it to True. This will update with the current timestamp each time you update the model. If you are setting the object as published in the Django admin, a nice way to do this is to override the save_model method of your model admin class.

Which ORM is best for Django? ›

6 of the best ORMs for Python
  • Django ORM.
  • Peewee.
  • PonyORM.
  • SQLAlchemy.
  • SQLObject.
  • Tortoise ORM.
Nov 15, 2023

Is Django ORM faster than SQL? ›

In cases where every millisecond of response time counts, custom-written SQL queries can often run faster than their ORM equivalents. This is because you can tailor your query to be as efficient as possible, cutting out any unnecessary steps that the ORM might include.

Is Django ORM a database? ›

Django's ORM provides a high-level abstraction of the database, which can make it easy to write code that generates inefficient SQL queries. To optimize database queries for performance, it's important to understand how the ORM generates SQL queries and how to write efficient database queries.

How to insert data in Django model? ›

Insert data into database in Django
  1. Inside the class "Meta", specify the model name and the fields you want to insert the data. ...
  2. Open the views.py file and create a function with the name addStudent as given in the path above.
  3. We have printed the variable form using the {{ }}.

How do you refresh a model object in Django? ›

Refreshing objects from database¶

If you need to reload a model's values from the database, you can use the refresh_from_db() method. When this method is called without arguments the following is done: All non-deferred fields of the model are updated to the values currently present in the database.

How do I update an instance in Django? ›

To update a model instance in Django, you typically retrieve the instance from the database, modify its fields, and then save it back to the database using the save() method.

Top Articles
Latest Posts
Article information

Author: Jamar Nader

Last Updated:

Views: 6446

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.