Django Tutorial Part 6: Making Queries (Django ORM)

Disclaimer: Your support helps keep JovialGuide running! Our content is reader-supported. This means if you click on some of our links, we may earn a commission.

The Django ORM is one of the best features of Django, because it provides an easy abstraction or layer to communicate with models. This means that you can easily communicate with the database and perform the standard CRUD operations using Django ORM alone. Django ORM comes with various APIs to Create, Read, Update and Delete without the need to learn SQL – Structured Query Language, which is the standard query language for communicating with databases.

Working with SQL requires proficiency in the query language. This simply means that you will have to learn the different queries available in SQL to be able to make proper communications with the database. These queries are complex and requires a lot of time to master. But Django provides us with an ORM, which is an abstraction that allows us easily communicate with the database.

In part 5 of this complete beginners guide to Django, we showed you how to create a superuser account, login to the Django admin site and how to work with the Django admin site, etc. In this complete beginners guide to Django part 6, we will show you how to work, and make queries with Django ORM (perform CRUD operations using Django ORM). This is a complete beginners guide to Django, so if you haven’t read part 5, then see part 5: working with the Django admin site or see part 1 – introduction to Django to get started.

What is Django ORM?

To communicate with a database, you will need an in-depth knowledge of SQL (Structured Query Language), which by default requires you to invest a lot of time in learning the different SQL statements. However, Django saves us the time of having to learn and master SQL, by introducing ORM. ORM is an acronym that stands for Object Relational Mapper.

Django ORM is an abstraction or layer for making queries or communicating with the database. It is the equivalent of SQL, except that you do not write actual SQL queries. Just like writing SQL queries, Django ORM comes with methods for Create, Read, Update and Delete (CRUD operations). These methods allow you easily perform complex operations as you would in SQL!

Django ORM is basically an equivalent to SQL queries, only that Django simplifies the ORM, by providing easy-to-understand commands for making SQL equivalent queries. This is so that you don’t have to learn another language or framework differently to communicate with the database, if you are a beginner.

When you make queries using Django ORM, the queries are converted to SQL equivalents and then used to Create Read, Update or Delete a record based on the query you make.

A Django ORM looks like this:

ModelAdmin.objects.operation()
  • ModelName is the name of the model you want to perform a query on
  • objects is a keyword
  • operation() is a method that represents an operation or query (create and read) you want to perform on the model

What is a QuerySet?

When you read a group of data from a Django model, the result is a queryset. So, a queryset is a list of objects retrieved from a Django model. In simpler words, the group of result gotten from a database table or model is a Django queryset.

Django queryset are gotten from models which are database tables.

A Django queryset looks like this:

<QuerySet [<ModelName: string_representation>, <ModelName: string_representation>, <ModelName: string_representation>]>
  • Note – a queryset is different from an object. When you fetch a single record, the result is an object, but when you fetch multiple records, the result is a queryset.

A queryset looks like this:

<QuerySet [<ModelName: string_representation>, <ModelName: string_representation>, <ModelName: string_representation>]>

While an object looks like this:

<ModelName: string_representation>

For this Django tutorial series, we encourage you to go to the Django admin site and create categories and articles for your models, as we will be making use of them in this series. If you are new to Django admin, see part 5 – working with the Django admin for more.

Django ORM: Retrieving All Records from a Model

Since we will make use of the Python shell throughout this part, run the following command to open Python shell (in your project folder where you have manage.py):

>>> python manage.py shell

There are times that you will want to read all records from a table. The Django ORM allows us to retrieve all records from a model using:

ModelName.objects.all()
  • ModelName is the name of the model that you want to retrieve records from. The all() method exposes use to all of the records in the model.

To retrieve all records from the Category model, copy and paste the following in the Python shell:

>>> from blog.models import Category
>>> all_categories = Category.objects.all()
>>> all_categories
<QuerySet [<Category: Education>, <Category: Sports>, <Category: Politics>, <Category: Entertainment>, <Category: Django>]>
  • The Python shell doesn’t have access to the Django models in your app, so you will start by importing the models you will use.

If the model you are trying to retrieve records from is empty, then your queryset will look like this:

<QuerySet []>

Django ORM: Retrieving a Single Record from a Model

The get() method allows us retrieve a single object from a model. It accepts a field as an argument, and returns an object not a queryset.

Copy and paste the following to retrieve the category with id=1 using the get() method:

>>> category = Category.objects.get(id=1) 
>>> category                             
<Category: Education>
  • The result gave us an object not a queryset
  • If no category with id=1 is found, it raises the DoesNotExist exception. However, if it finds multiple records (which is a queryset), then it raises the MultipleObjectReturned exception. This means that you can’t retrieve different records with the same value using get()
  • The id field is usually unique=True, so you might not encounter the MultipleObjectReturned exception when you retrieve a single record using the id field (see part 4 for Django field options). The MultipleObjectReturned exception will not be raised on your id field as long as unique=True
  • If it raises the DoesNotExist exception, it means that there is no object with the id of 1 in your table. You can try other ids till you find an id that do exists

Django ORM: Retrieving and Updating an Object

We will retrieve an object using the get() method then update it.

Run the following command using the get() method to retrieve an object then update it:

>>> category = Category.objects.get(id=1) 
>>> category
<Category: Education>
>>> category.title = 'Edited - Education'
>>> category.title
'Edited - Education'
>>> category.status = 'unpublished'
>>> category.status
'unpublished'
>>> category.description = 'This is an edited category description for education'
>>> category.description                                           
'This is an edited category description for education'
  • After retrieving the object with the id=1 using the get() method, we access the category fields we want to update using the dot notation (.), followed by the field name we want to update, an assignment operator then the new value that we want to assign to the field

Django ORM: Saving an Object

Up un-till now, we have edited our fields without saving. This means that we will loose the changes we have made to the fields if we exist the Python shell without saving.

To save an object, Django ORM gives us the save() method to save the changes we have made to an object.

Run the following command to save the category object:

>>> category.save()

That is how to save an object in Django ORM.

Django ORM: Creating an Object

Django ORM allows us create an object using the create() method. This method accepts fields that are present in the model.

Run the following command to create a category object:

>>> Category.objects.create(title='Chemistry', description='Chemistry category description', status='unpublished')
<Category: Chemistry>

We can also create an object using Django ORM like the syntax below:

>>> new_category = Category(title='Test', description='Category description', status='unpublished')
>>> new_category.save()
>>> new_category
<Category: Test>
  • Notice we didn’t pass the created_at and the updated_at fields while creating a category object. This is because the created_at field has auto_now_add=True while the updated_at field has auto_now=True (see part 4 for Django field options). These fields are automatically updated by Django.
  • In the first example, the object is saved automatically without calling the save() method. While the second example requires us to call the save() method for the object to save

You can use variables, thus:

>>> category_title = 'Music'
>>> category_description = 'Music category description'
>>> category_status = 'published'
>>> Category.objects.create(title=category_title, description=category_description, status=category_status)
<Category: Music>
  • Notice that we did not enclose category_title, category_description and category_status in quotation marks (‘…’ or “…”). This is because they are variables – containers for storage. So, adding quotation marks around them will cause them to become strings (text), meanwhile we want them to be variables.

Django ORM: Deleting an Object

We can use the delete() method of the Django ORM to delete an object. First retrieve the object then apply the delete() method.

Run the following command to delete the category object with id=4:

>>> category = Category.objects.get(id=4)
>>> category.delete()
(1, {'blog.Category': 1})

Django ORM: Filtering a QuerySet (Published Categories)

Django ORM exposes us to filter() method, which allows us retrieve or filter queryset that meet a particular condition. It accepts fields as arguments (multiple fields are supported, separate with commas: Model.objects.filter(field=condition, another_field=another_condition)), and returns a queryset.

Run the following command to filter only published categories:

>>> published_categories = Category.objects.filter(status='published')
>>> published_categories                                                
<QuerySet [<Category: Entertainment>, <Category: Django>, <Category: Politics>, <Category: Music>]>

Django ORM: Filtering a QuerySet (Unpublished Categories)

Run the following command to filter only unpublished categories:

>>> unpublished_categories = Category.objects.filter(status='unpublished')
>>> unpublished_categories                                                
<QuerySet [<Category: Education>, <Category: Chemistry>, <Category: Test>]>

Django ORM: Counting a QuerySet

We will count the number of categories in the Category model. This is done using the count() method of Django ORM.

Run the following command to count the number of categories in the Category model:

>>> Category.objects.all().count()
7
  • The count() method is the equivalent of COUNT() function in SQL

Django ORM: Limiting a QuerySet

Django ORM allows us to limit queryset to whatever limit or number we want using Python list slice. This is the equivalent to SQL’s LIMIT keyword.

Run the following command to limit the Category queryset to 2 (two):

>>> Category.objects.all()[:2]
<QuerySet [<Category: Edited - Education>, <Category: Politics>]>

Django ORM: Ordering a QuerySet (Ascending and Descending)

With Django ORM’s order_by() method, you can order a queryset in ascending or descending order. The order_by() method is the equivalent to the ORDER BY keyword in SQL.

Run the following command to order a queryset in ascending order:

>>> Category.objects.all().order_by('id')
<QuerySet [<Category: Education>, <Category: Entertainment>, <Category: Chemistry>, <Category: Test>, <Category: Django>, <Category: Politics>, <Category: Music>]>

To order a queryset in descending order, use the minus () sign in front of the field.

Run the following command to order a queryset in descending order:

>>> Category.objects.all().order_by('-id')  
<QuerySet [<Category: Music>, <Category: Politics>, <Category: Django>, <Category: Test>, <Category: Chemistry>, <Category: Entertainment>, <Category: Education>]>

Django Tutorial Series

In this complete beginners guide to Django, we have been able to cover part 1 – part 6. If you need to read them again, or have not read them yet, please see:

In the next complete beginners guide to Django, we will show you:

We hope this complete beginners guide to Django – making queries with Django ORM (part 6) helped you learn how to work, and make queries with Django ORM. This is a complete beginners guide to Django, so if you haven’t read part 5, then see part 5: working with the Django admin site or see part 1 – introduction to Django to get started.

See other of our Django tutorials for more.

You Might Also Like

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Shares