Open In App

Django ORM - Inserting, Updating & Deleting Data

Last Updated : 14 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Django's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and database tables, making it easy to create, retrieve, update, and delete data in the database.

Defining the Models

Let’s start with the following models representing a music application where we have 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.

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

Django ORM Queries

Inserting Data with Django ORM

1. 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()

2. 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.

Retrieving Data with Django ORM

1. 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. Notice that the __str__() method is used to print the album title.

2. 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.

3. 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.

4. 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>

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

Updating Data with Django ORM

1. 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.

2. 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".

Deleting Data with Django ORM

1. 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.

2. 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.

Django ORM Query Methods Summary

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

Next Article
Practice Tags :

Similar Reads