Django Tutorial for beginners [step by step] part 6 – Django ORM

tutorial goal: Learn to work with Django ORM. Add, modify, delete data.

Welcome to tutorial part 6. In this tutorial, we are going to learn how to use the ORM to interact with our database.

What is Django ORM


Orm stands for an Object-relational mapper. The Object-Relational Mapper (ORM) is one of Django’s most powerful features, allowing you to interact with your database in the same way that you would with SQL. In truth, Django’s ORM is essentially a pythonic technique to build SQL to query and edit your database and obtain results. it’s actually some pretty brilliant engineering that leverages some of Python’s more sophisticated features to make developers’ life easier. Django ORM is designed to handle queries of low to medium complexity.

In the previous tutorial, we have created a model and migrated it to our database which is the default Django database called SQLite. By migrating the model a table will be created in the database.

from django.db import models

class Artist (models.Model):
    name = models.CharField(max_length = 250)
    country = models.CharField(max_length = 150)
    birth_year = models.IntegerField()
    genre = models.CharField(max_length = 150)

Django makes it easy for us to interact with database models, i.e. modify, delete, add and query objects. Orm is for interacting with the database and plays a role like a bridge between the database and our code.

Django shell

It allows us to save, update and retrieve our models in our code. Interacting with databases while working with projects in production is very essential and unavoidable.
The key benefit of ORMs is their ability to develop quickly. ORMs increase the portability of a project. If we use ORMs, changing the database is a lot easier. We can access the ORM by running Python manage.py shell from the main directory of our Django project.

python manage.py shell
Python 3.8.10 (default, Sep 28 2021, 16:10:42) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

Python manage.py automatically set up and import the setting and configuration of our Django project.

The first thing we need to do is import our artist model in the shell in order to use it and interact with it.

>>> from musiclib.models import Artist

This .models refers to the models.py file inside our app and the artist is the class name of our model.
Let’s say we want to retrieve all of the rows of objects inside the table of artist in the database.
what we do is:

Article.objects.all()

Which retrieve all objects as follows:

<QuerySet [<Artist: Artist object (1)>, <Artist: Artist object (2)>, <Artist: Artist object (3)>, <Artist: Artist object (4)>]>

We can also access the first item in the table by using the index number and name property like this:

Artist.objects.all()[0].name
>>>'freddie mercury'

When we are retrieving the data like this:

<QuerySet [<Artist: Artist object (1)>, <Artist: Artist object (2)>, <Artist: Artist object (3)>

It’s a bit difficult for us to make sense of the retrieved data. Instead of the artist’s object, It’s better to see the name of the artist. for this purpose, we need to add a function to our model in the models.py file. Open the models.py and add this function underneath the class:

Str() function

class Artist (models.Model):
    name = models.CharField(max_length = 250)
    country = models.CharField(max_length = 150)
    birth_year = models.IntegerField()
    genre = models.CharField(max_length = 150)

    def __str__(self):
        return self.name

This is a built-in function in Django that defines how an instance of a model looks both in the admin section and also in the shell which we just did it.
this function takes in a self parameter which instance of the Artist and then returns the name of self.

Filter the data

This filter() function returns a string version of the name of any instances of this model both the ones that have been created previously or will be created in the future when we retrieve it.
Save the code and run shell again:

&gt;&gt;&gt; from musiclib.models import Artist
&gt;&gt;&gt; Artist.objects.all()
&lt;QuerySet [&lt;Artist: freddie ercury&gt;, &lt;Artist: michael jackson&gt;, &lt;Artist: Kurt Cobain&gt;, &lt;Artist: Roger Waters&gt;]&gt;
&gt;&gt;&gt; 

Django also provides some function to filter data like filter(), exclude(),get(). The filter() function returns a QuerySet with objects that match the lookup parameters passed in. for example:

>>> Artist.objects.filter(country='USA')
<QuerySet [<Artist: michael jackson>, <Artist: Kurt Cobain>]>
>>> 

By passing the country parameter to the filter() we tell Django to give us the artists that their country is saved USA in the database.
The filter function is case-sensitive. For example, if the country field is in capital letters, you need to pass it to filter in capital and if not you may get an error.

You can filter a model by passing each field of the model as a parameter into the function filter. In our case, they are name, country, genre, birth year. Also, you can pass one, two, or more parameters at the same time for example:

>>> Artist.objects.filter(country='England',genre="rock")
<QuerySet [<Artist: freddie ercury>, <Artist: Roger Waters>]>
>>> 

exclude()

The exclude() function returns a QuerySet having objects other than those matching the passed-in parameters.

>>> Artist.objects.exclude(genre="rock")
<QuerySet [<Artist: michael jackson>, <Artist: Kurt Cobain>]>
>>> 

Modifying the objects

Sometimes we want to modify and change the objects of a model. for example we want to change the michael jackson genre to rock
we can do this as follows:

>>> artist = Artist.objects.get(name='michael jackson')
>>> artist.genre= "rock"
>>> artist.save()

Deleting the objects

we can also delete instances of the model. For example, we want to delete the artists with the pop genre.

>>> artist =  Artist.objects.get(name='Roger Waters')
>>> artist.delete()

If you retrieve all the objects:

>>> Artist.objects.all()
<QuerySet [<Artist: freddie ercury>, <Artist: Kurt Cobain>]>,<Artist: roger waters>]>

As you can see the artist with the pop genre which in our case micheal jackson is deleted from the database.

Create a new instance

We made our instances via the admin section but we can also create new instances with ORM. It’s very simple you just need to define an instance and save it like this:

artist1 = Artist()
artist.save()

This is going to create an artist in our database, but this does not have any properties like name, birth year genre. so let’s give our instance properties which we need to add to it now or later.

If you wish to join a community of self-starters learning new skills and creating projects from scratch, join our Discord channel here and share your passion.

This is the end of the part 6 tutorial. I hope you find it useful. See you in the next parts. 🙂

NEXT

Django Tutorial for beginners [step by step] part 7 – staticfiles in Django

PREVIOUS:

Django Tutorial for beginners [step by step] part 5 – creating URL, view, template

Please do tell us, did you find the content above helpful?