Open In App

Django ORM - Inserting, Updating & Deleting Data

Last Updated : 28 Oct, 2025
Comments
Improve
Suggest changes
50 Likes
Like
Report

Django’s ORM simplifies database interactions by allowing developers to work with Python classes instead of writing raw SQL queries.

Key Features:

  • Defines the database schema using Python classes (models).
  • Bridges the gap between Python objects and database tables.
  • Enables creating, retrieving, updating, and deleting data easily.
  • Eliminates the need to write raw SQL for common database operations.

Steps to Use Django ORM

The following steps demonstrate how to define models, interact with the database, and perform common operations using Django ORM.

Step 1. Defining the Models

Let’s create models for a music application with albums and songs:

Python
class Album(models.Model):
    title = models.CharField(max_length = 30)
    artist = models.CharField(max_length = 30)
    genre = models.CharField(max_length = 30)

    def __str__(self):
        return self.title

class Song(models.Model):
    name = models.CharField(max_length = 100)
    album = models.ForeignKey(Album, on_delete = models.CASCADE)

    def __str__(self):
        return self.name
  • The Album model has fields for title, artist, and genre.
  • The Song model contains a name field and a foreign key linking each song to an album.
  • on_delete=models.CASCADE ensures that if an album is deleted, all its songs are also deleted.
  • The __str__() method returns a readable string representation of the object.

Step 2. Accessing the Django ORM via Django Shell

To interact with Django’s ORM, we use the Django shell. Run the following command to open an interactive Python shell in the context of your Django project:

python manage.py shell

we can import our models using the following command:

>>> from books.models import Song, Album

DjangoShell
Django Shell

Step 3. Django ORM Queries

1. Inserting

Creating and Saving a Single Object: To create and save an Album object to the database, use the following command.

>>> a = Album(title="Divide", artist="Ed Sheeran", genre="Pop")
>>> a.save()

Similarly, to create and save a Song object associated with the previously created Album:

>>> s = Song(name="Castle on the Hill", album=a)
>>> s.save()

Inserting Multiple Records: Let’s add a few more albums to the database.

>>> a1 = Album(title="Abbey Road", artist="The Beatles", genre="Rock")
>>> a1.save()

>>> a2 = Album(title="Revolver", artist="The Beatles", genre="Rock")
>>> a2.save()

Here, we’ve added two more albums, both by The Beatles. Each call to save() writes the object to the database.

2. Retrieving

Retrieving All Records: To retrieve all records from the Album model, we use the all() method.

>>> Album.objects.all()
<QuerySet [<Album: Divide>, <Album: Abbey Road>, <Album: Revolver>]>

The QuerySet is a list-like object containing all the Album instances. The __str__() method is used to print the album title.

Filtering Records: You can filter records based on specific conditions using the filter() method.

>>> Album.objects.filter(artist="The Beatles")
<QuerySet [<Album: Abbey Road>, <Album: Revolver>]>

In this example, we retrieve albums by The Beatles.

Excluding Records: The exclude() method allows you to retrieve all records except those that match a condition.

>>> Album.objects.exclude(genre="Rock")
<QuerySet [<Album: Divide>]>

Here, we exclude albums with the genre Rock and retrieve the remaining albums.

Retrieving a Single Record: To retrieve a single object based on a unique field, use get(). Note that this will raise an exception if multiple objects match.

>>> Album.objects.get(pk=3)
<Album: Revolver>

Here, we're retrieving the album with primary key (pk) 3, which is Revolver.

3. Updating

Modifying an Existing Object: To update an existing record, first retrieve the object, modify its attributes, and then save it.

>>> a = Album.objects.get(pk=3)
>>> a.genre = "Pop"
>>> a.save()

This changes the genre of the album Revolver to 'Pop' and saves the update to the database.

Bulk Update: You can also update multiple objects at once using update().

>>> Album.objects.filter(artist="The Beatles").update(genre="Classic Rock")

This will update the genre of all albums by The Beatles to 'Classic Rock'.

4. Deleting

Deleting a Single Record: To delete a specific record, first retrieve the object and then call the delete() method.

>>> a = Album.objects.get(pk=2)
>>> a.delete()

After running this, the album with pk=2 (e.g., Abbey Road) will be deleted from the database.

Deleting Multiple Records: To delete multiple records at once, use filter() or exclude() combined with the delete() method.

>>> Album.objects.filter(genre="Pop").delete()

This will delete all albums with the genre 'Pop'. Be cautious as this operation cannot be undone.

Common Django ORM Query Methods

  • .all(): Retrieve all objects of a model.
  • .filter(): Retrieve objects that match specific conditions.
  • .exclude(): Retrieve objects that do not match specific conditions.
  • .get(): Retrieve a single object that matches the condition (raises an error if multiple objects match).
  • .update(): Update multiple objects at once.
  • .delete(): Delete records from the database

Explore