Wednesday, December 25, 2024
Google search engine
HomeLanguagesDjango ORM – Inserting, Updating & Deleting Data

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

Django ORM

Django’s Object-Relational Mapping (ORM) system, a fundamental component that bridges the gap between the database and the application’s code. This article delves into the intricate realm of Python, Django, and their ORM, uncovering how this technology stack simplifies database interactions and accelerates the development process. For demonstration purposes, we will use the following Django models.

Python3




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


Django Shell

We can access the Django ORM by running the following command inside our project directory.

python manage.py shell

This brings us to an interactive Python console. Assuming that our models exist in

myProject/albums/models.py

we can import our models using the following command:

>>> from books.models import Song, Album

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 []>

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments