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 ModelsLet’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
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:
Django Shell Django ORM Queries Inserting Data with Django ORM>>> from books.models import Song, Album
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 ORM1. 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 ORM1. 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 ORM1. 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 SummaryRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4