Django Tutorial for Beginners [Step by Step] – Part 6: Django ORM.
Welcome to Part 6 of our Django tutorial.
In this tutorial, you’ll learn how to interact with a database using Django’s Object-Relational Mapper (ORM). By the end, you’ll be able to add, modify, delete, and query data efficiently.
Prerequisites
- Knowledge of creating a basic Django project
- Knowledge of Django's Model-View-Template (MVT) architectural pattern
Refer to parts 1 - 5 of this tutorial series to get a basic understanding of the above.
What is Django ORM?
ORM (Object-Relational Mapper) is one of Django’s most powerful features. Django’s ORM is a pythonic technique to build SQL to query and edit your database and obtain results.
It provides a Pythonic way to interact with databases and eliminates the need to write raw SQL queries. Instead, you use Python code to add, retrieve, update, and delete records in the database.
Django ORM is designed to handle queries of low to medium complexity.
Benefits of Django ORM
- Simplifies database operations: No need for complex SQL queries.
- Database portability: Switch between databases (SQLite, PostgreSQL, MySQL) with minimal changes.
- Faster development: Write less boilerplate code.
Understanding our model
In the previous tutorial, we 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.
model.py:
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)
This model defines an Artist with attributes for name, country, birth year, and genre.
Django makes it easy for us to interact with database models, i.e., modify, delete, and add query objects. ORM is for interacting with the database and acts as a bridge between the database and our code.
Interacting with the Database via Django shell
Django provides an interactive shell where you can run Python commands to interact with your database.
It allows you to save, update, and retrieve our models in our code.
We can access the ORM by running this code from the main directory of our Django project.
python manage.py shell
Django will automatically set up and import the settings and configuration of your Django project.
Querying Data
The first thing we need to do is import our artist model into the shell in order to use it and interact with it.
Then we want to retrieve all of the rows of objects inside the table of artists in the database.
Do these using the following code:
from musiclib.models import Artist
Article.objects.all()
It will retrieve the objects like this:
<QuerySet [<Artist: Artist object (1)>, <Artist: Artist object (2)>, <Artist: Artist object (3)>, <Artist: Artist object (4)>]>
To get the first artist using the index number and name property, do this:
Artist.objects.all()[0].name
Result will be:
'freddie mercury'
It’s a bit difficult for us to make sense of the retrieved data if we retrieve it the way we did. 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:
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
Each artist is displayed using the __str__() method, making it easier to read.
This uses the __str__() built-in function in Django to define how an instance of a model looks both in the admin section and also in the shell, which we just did.
This function takes in a self parameter, which is an instance of the artist, and then returns the name of self.
Filtering Data
Django provides filtering methods to query specific records.
Filter by a single condition
For example, let's say we want to get all artists from the USA.
By passing the country parameter to the filter() we tell Django to get us the artists that their country is saved USA in the database.
Artist.objects.filter(country='USA')
Note: The filter() method is case-sensitive, so "USA" and "usa" are treated differently.
The above code will return the result below since there are only two artists with country USA
<QuerySet [<Artist: Michael Jackson>, <Artist: Kurt Cobain>]>
Filter by multiple conditions
For example, let's say we want to get all rock artists from England. We can do something like this:
Artist.objects.filter(country='England', genre="rock")
And we'd get this:
<QuerySet [<Artist: freddie mercury>, <Artist: Roger Waters>]>
Excluding Data
The exclude() function returns a QuerySet having objects other than those matching the passed-in parameters.
For example, to exclude rock artists:
Artist.objects.exclude(genre="rock")
The result will be:
<QuerySet [<Artist: michael jackson>, <Artist: Kurt Cobain>]>
Modifying Data
Sometimes we want to modify and change the existing records or objects of a model.
For example, let's say we want to change Michael Jackson's genre to rock.
We can do this as follows:
artist = Artist.objects.get(name='michael jackson')
artist.genre = "rock"
artist.save()
Deleting Data
We can also delete instances of the model. For example, we want to delete the artists with the pop genre.
We can simply use this code:
artist = Artist.objects.get(name='Roger Waters')
artist.delete()
Now, if you retrieve all artists:
Artist.objects.all()
You get:
<QuerySet [<Artist: Freddie Mercury>, <Artist: Kurt Cobain>]>
The artist Roger Waters has been removed.
Create a New Instance
We created our instances (artists) using the Django admin 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 empty artist data in our database, which will not have any properties like name, country, birth year, or genre.
If you wish to add properties while creating it at once, use this instead:
artist1 = Artist(name="Elton John", country="UK", birth_year=1947, genre="Pop")
artist.save()
Now if you check all the artists, you'll see the newly created artist data added to the new database query list.
Conclusion
You’ve learned how to:
- Retrieve data with all(), filter(), exclude()
- Modify records with .save()
- Delete records with .delete()
- Create new records with .save()
Next:
Django Tutorial for Beginners [Step by Step] – Part 7: Staticfiles in Django.
If you wish to join a community of self-starters learning new skills and creating projects from scratch, join our Discord channel and share your passion.