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 the Django ORM alone. The 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 Django tutorial series for beginners, 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 Django tutorial series for beginners part 6, we will show you how to work, and make queries with the Django ORM (perform CRUD operations using the Django ORM). This is a Django tutorial series for beginners, so if you haven’t read part 5, then see part 5: working with the Django admin site to get started.

What is the 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 which are complex. 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. The Django ORM is the equivalent of SQL, except that you do not write actual SQL queries. Just like writing SQL queries, the 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!

The 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.

When you make queries using the Django ORM, the queries are converted to their 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()

[/code]

  • 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.

    Django queryset is gotten from model which is a database table. The group of result gotten from a database table or model is a Django queryset.

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

    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.

    Django ORM: Retrieving All Records from a Model

    Since we will make use of the Python shell throughout this series, run the following command to open the 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 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 which 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: Entertainment>, <Category: Technology>, <Category: Education>]>
    

    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: Entertainment>
    

    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 store different records with the same id.

    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 and object using the get() method then update it.

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

    >>> category = Category.objects.get(id=1) 
    >>> category
    <Category: Entertainment>
    >>> category.title = 'Edited - Entertainment'  
    >>> category.title
    'Edited - Entertainment'
    >>> category.description = 'This is an edited category description for entertainment'
    >>> category.description                                           
    'This is an edited category description for entertainment'
    

    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, the 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

    The Django ORM allows us create an object using the create() method. This method accept 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='draft')
    <Category: Chemistry>
    

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

    >>> new_category = Category(title='Test', description='Category description', status='published')
    >>> 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).

    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, {'new.Category': 1})
    

    Django ORM: Filtering a Queryset

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

    Run the following command to filter only published categories:

    >>> published_categories = Category.objects.filter(status='published')
    <QuerySet [<Category: Edited - Entertainment>, <Category: Education>, <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 the Django ORM.

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

    >>> Category.objects.all().count()
    3
    

    The count() method is the equivalent of the COUNT() function in SQL.

    Django ORM: Limiting a QuerySet

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

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

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

    Django ORM: Ordering a QuerySet (Ascending and Descending)

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

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

    >>> Category.objects.all().order_by('id')
    <QuerySet [<Category: Technology>, <Category: Education>, <Category: Chemistry>, <Category: Test>]>
    

    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: Test>, <Category: Chemistry>, <Category: Education>, <Category: Technology>]>
    

    Django Tutorial Series

    In this Django tutorial series for beginners, 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:

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

    See other of our Django tutorials for more.

Leave a Reply

Your email address will not be published. Required fields are marked *

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