Django ORM Queries
Insert Data with Django ORM
To create an object of model Album and save it into the database, we need to write the following command:
>>> a = Album(title = "Divide", artist = "Ed Sheeran", genre = "Pop") >>> a.save()
To create an object of model Song and save it into the database, we need to write the following command:
>>> s = Song(name = "Castle on the Hill", album = a) >>> s.save()
Creating Data with Django ORM
Let us add 2 more Albums records for the sake of demonstration.
>>> a = Album(title = "Abbey Road", artist = "The Beatles", genre = "Rock") >>> a.save() >>> a = Album(title = "Revolver", artist = "The Beatles", genre = "Rock") >>> a.save()
Retrieving Data with Django ORM
To retrieve all the objects of a model, we write the following command:
>>> Album.objects.all() <QuerySet [<Album: Divide>, <Album: Abbey Road>, <Album: Revolver>]>
The output is a QuerySet, or a set of objects that match the query. Notice that the name printed is the output of the __str__()
function. We can also filter queries using the functions filter()
, exclude()
and get()
. The filter()
function returns a QuerySet having objects that match the given lookup parameters.
>>> Album.objects.filter(artist = "The Beatles") <QuerySet [<Album: Abbey Road>, <Album: Revolver>]>
The exclude()
function returns a QuerySet having objects other than those matching the given lookup parameters.
>>> Album.objects.exclude(genre = "Rock") <QuerySet [<Album: Divide>]>
The get()
function returns a single object which matches the given lookup parameter. It gives an error when the query returns multiple objects.
>>> Album.objects.get(pk = 3) <QuerySet [<Album: Revolver>]>
Update Data with Django ORM
We can modify an existing object as follows:
>>> a = Album.objects.get(pk = 3) >>> a.genre = "Pop" >>> a.save()
Deleting Data with Django ORM
To delete a single object, we need to write the following commands:
>>> a = Album.objects.get(pk = 2) >>> a.delete() >>> Album.objects.all() <QuerySet [<Album: Divide>, <Album: Revolver>]>
To delete multiple objects, we can use filter()
or exclude()
functions as follows:
>>> Album.objects.filter(genre = "Pop").delete() >>> Album.objects.all() <QuerySet []>
Django ORM – Inserting, Updating & Deleting Data
Django lets us interact with its database models, i.e. add, delete, modify, and query objects, using a database-abstraction API called ORM(Object Relational Mapper). This article discusses all the functional operations we can perform using Django ORM.
Prerequisite: Django models