Django ORM - Inserting, Updating & Deleting Data
Last Updated :
14 May, 2025
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
Django ShellDjango 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.
Similar Reads
Django Models
A Django model is a Python class that represents a database table. Models make it easy to define and work with database tables using simple Python code. Instead of writing complex SQL queries, we use Djangoâs ORM (Object Relational Mapper), which allows u to interact with the database in a more read
8 min read
Django ORM - Inserting, Updating & Deleting Data
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 databas
4 min read
Django Basic App Model - Makemigrations and Migrate
Django's Object-Relational Mapping (ORM) simplifies database interactions by mapping Python objects to database tables. One of the key features of Django's ORM is migrations, which allow you to manage changes to the database schema.What are Migrations in Django?Migrations are files that store instru
4 min read
Add the slug field inside Django Model
The slug field within Django models is a pivotal step for improving the structure and readability of URLs in web applications. This addition allows developers to automatically generate URL-friendly slugs based on titles, enhancing user experience and search engine optimization (SEO). By implementing
4 min read
Intermediate fields in Django - Python
Prerequisite: Django models, Relational fields in DjangoIn Django, a many-to-many relationship is used when instances of one model can be associated with multiple instances of another model and vice versa. For example, in a shop management system:A Customer can purchase multiple Items.An Item can be
2 min read
Uploading images in Django - Python
Prerequisite - Introduction to DjangoUploading and managing image files is a common feature in many web applications, such as user profile pictures, product images, or photo galleries. In Django, you can handle image uploads easily using the ImageField in models.In this article, weâll walk through a
3 min read
Change Object Display Name using __str__ function - Django Models | Python
How to Change Display Name of an Object in Django admin interface? Whenever an instance of model is created in Django, it displays the object as ModelName Object(1). This article will explore how to make changes to your Django model using def __str__(self) to change the display name in the model. Ob
2 min read
Custom Field Validations in Django Models
In Django, field validation is the process of ensuring that the data entered into a field meets certain criteria. Custom field validation allows us to enforce rules such as checking for specific formats, length restrictions or even more complex conditions, like validating an email to belong to a spe
3 min read
Meta Class in Models - Django
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. Itâs free and open source. D
3 min read
How to use Django Field Choices ?
Djangoâs choices option lets you limit a model field to a fixed set of values. It helps keep your data clean and consistent, and automatically shows a dropdown menu in forms and the admin instead of a text box.Choices are defined as pairs: the first value is saved to the database, and the second is
2 min read