Django ORM Basics Part 1

Having learned the art of creating models, let’s now shift our attention on how to insert and access the data from the database. Django ORM provides an elegant and powerful way to interact with the database. ORM stands for Object Relational Mapper. It is just a fancy word describing how to access the data stored in the database in Object Oriented way instead of executing SQL.

Start the Django shell using the shell command.

To work with the database inside the shell, first, we have to import necessary models. In this chapter, we will be working on models stored in the djangobin app, so let’s start by importing all the models from the djangobin app.

At this point, the tables corresponding to these models are empty.

Let’s create an Author object.

Try printing the variable a and you will get the following output:

Note that the string representation of the author is coming from the __str__() method in the Author model. If we had not defined the __str__() method, we would get the output as follows:

You can access the attributes of an object using the dot (.) operator.

Note that at the time of creating Author object we didn’t provide any value to created_on and last_logged_in field because these fields have auto_now_add and auto_now set to True. As a result, Django will automatically provide the current date and time when you save the object to the database. However, If we hadn’t set auto_now_add and auto_now parameters then we would have to pass values to created_on and last_logged_in fields as follows:

Note that here I am using django.utils.timezone module instead of Python’s builtin datetime module. This is because django.utils.timezone module generates a timezone aware datetime.datetime objects by default (due to USE_TZ = True in settings.py file).

Another important thing to notice in the preceding snippet is that we are just passing the name of the function (timezone.now) to created_on and last_logged_in arguments instead of actually calling it. This allows Django to call timezone.now() at the time of inserting a new record.

At this point, the object pointed to by variable a exist only inside the Django shell. To save the object to the database call the save() method.

Recall that every model we define inherits from models.Model class, this is where the save() method comes from.

To view this newly added object open djangobin_author table inside Navicat.

Similarly, models.Model class also provides a delete() method to delete an object from the database.

This code removes author tom from the database. However, it still exists inside the shell.

Let’s save it again by calling the save() method.

When you save an object the primary key is assigned automatically. You can refer to the primary key using id or pk attribute.

If you want to alter the attributes of an object just assign new the values and call the save() method again.

These changes are not yet saved to the database. To do so, call the save() method.

Database Access through Managers

Django by default adds a manager called objects to every model class. The objects manager helps us to query the database in all sorts of ways.

To access the objects manager type model class followed by the (.) dot operator then the objects manager itself. For example:

As you can see, the objects is just an instance of django.db.models.manager.Manager class. The objects manager provides a whole range of methods which allows us to interact with the database easily.

Let’s discuss some important methods of the objects manager.

The create() method

The create() method allows us to create and commit object to the database in one go, instead of separately calling the save() method. For example:

The bulk_create() method

The bulk_create() method allows us to create and commit multiple objects. It accepts a list of objects. For example:

At this point, the djangobin_author table should look like this:

The all() method

The all() method fetches all the records from the table. For example:

This query returns all the records from the djangobin_author table.

The all() method returns a QuerySet object. A QuerySet object looks a lot like a list, but it is not an actual list, however, in some ways, it behaves just like a list. For example, you can access individual members in a QuerySet objects using an index number.

Although, variable l points to an object of type QuerySet but l[0], l[1], l[2] and so on, points to an object of type Author.

A QuerySet object is of special importance in Django. We use it to filter, order and slice the results. As we will see, there are many other methods that return a QuerySet object.

The QuerySet object is iterable just like a list. You can use a for loop to iterate through all of the objects in it.

The count() method

The count() method returns the total number of records returned by the query.

This query isn’t qualified in any way that’s why it returns the count of all records in the table. The preceding query is functionally equivalent to following:

Filtering records using the filter() method

Most of the time you would only want to work with a subset of data. In Django, that’s the job of filter() method. It accepts field names as keyword arguments and returns a QuerySet containing objects that match the given criteria.

The query Author.objects.filter(name='tommy') translates to SQL roughly as follows:

As database has only one record where the name is 'tommy', the QuerySet object contains only a single Author object. If we had two records where the name is 'tommy' then filter() would have returned a QuerySet containing two Author objects.

Similarly, Author.objects.filter(name='johnny') translates to SQL roughly as follows:

As there are no records where the name is 'johnny' an empty QuerySet is returned.

We can also directly print the raw SQL Django uses to query the database using the query attribute of the QuerySet object.

Matching performed using keyword arguments are case-sensitive.

The last query returns an empty QuerySet because there are no records where email is "JERRY@mail.com", however, there is a record where the email is "jerry@mail.com".

You can also pass multiple keyword arguments to the filter() method. When we do so, keyword arguments are ANDed together.

This query translates to SQL roughly as follows:

Excluding records with the exclude() method

The exclude() method is just the opposite of the filter() method. It returns a QuerySet only containing the objects that do not match the given parameters.

This query translates to SQL roughly as follows:

Get Object by Primary Key

As already discussed, Django automatically adds a primary key field called id to the every model class. You can use id field or its alias pk to access an object by its primary key. For example:

Field Lookups

In addition to passing field names as keyword arguments. You can also use something called lookups to filter to result further. A lookup is composed of a model field followed by two underscores (__), followed by the lookup name. Lookups are also passed as keyword arguments.

contains lookup

The contains lookup performs a case-sensitive containment test. For example:

In this query, the contains lookup finds all the objects where the name field contains the string "ke" at the beginning, or end, or somewhere in between.

The query Author.objects.filter(name__contains="ke") translates to SQL roughly as follows:

Matching performed by contains lookup is case-sensitive.

icontains lookup

Works just like contains but perform a case-insensitive match.

SQLite database doesn’t support case-sensitive LIKE statements. As a result, contains and icontains lookups will return the same result.

startswith lookup

The startswith lookup performs a case-sensitive start-with. For example:

In this query, the startswith lookup finds all the records whose name field start with the string "t".

The SQL equivalent of the above query is:

There also exists a complementary lookup called endswith.

endswith lookup

It performs a case case-sensitive end-with. For example:

Here the endswith lookup finds all the records whose email ends with "com".

The SQL equivalent of the above query is:

The startswith and endswith are both case-sensitive. Their case-insensitive equivalents are istartswith and iendswith.

gt lookup

Greater than:

In this query, the gt lookup finds all the records whose id or primary key (pk) is greater than 3.

The SQL equivalent of the above query is:

There also exists a complementary lookup called lt (less than).

lt lookup

Less than:

Here the lt lookups find all the records whose primary key is less than 3.

The SQL equivalent of the above query is:

There are two more similar lookups called gte (greater than or equal to) and lte (less than or equal to) which finds the records which are greater than or equal to and less than or equal to, respectively.

You can also pass multiple lookups at once. When we do so, lookups and ANDed together.

The SQL equivalent of the above query is:

exact lookup

The exact lookup performs a case-sensitive exact match: For example:

This query returns any object where name is spike. The SQL equivalent of the query is as follows:

The important thing to keep in mind is that if you don’t specify any lookup in your queries, Django will implicitly apply the exact lookup. This means that the preceding query can also be written as follows:

iexact lookup

Same as exact lookup but performs a case-insensitive match.

isnull lookup

The isnull lookup takes True or False, and adds IS NULL or IS NOT NULL operators to the query respectively.

The SQL equivalent of the preceding two queries is as follows:

in lookup

The in lookup finds all the values specified in the list. For example:

The preceding query returns Author objects whose name is either spike or tyke.

The SQL equivalent of the query is:

date, month and year lookups

The day, month and year lookups perform exact day, month and year match respectively. For example:

This query returns all Author objects which are created in the year 2018.

This query returns all the objects which are created in the March 2018.

This query returns all the objects which are created on the 24th March 2018.

Chaining QuerySet

It is also possible to chain multiple QuerySet objects to get exactly what you are looking for. For example:

In this query, we first create a QuerySet containing objects with the primary key greater than 1. Then we exclude all objects where the name is spike. Finally, we filter only the objects which contain the character 'o' in their name.

Chaining is particularly useful when you are applying some logic while building up the query. For example:

Getting the first and the last result

The first() and last() methods returns the first and last result from the QuerySet respectively.

Retrieving a single object using the get() method

The filter() method described in the above section returns a QuerySet, sometimes we just want to fetch a single record from the table. To handle these situations the objects manager provides a get() method. The get() method accepts same parameters as filter() method but it returns only a single object. If it finds multiple objects it raises a MultipleObjectsReturned exception. If it doesn’t find any object it raises DoesNotExist exception.

Notice the difference between the output of get() and filter() method. For the same parameter, they both return two different results. The get() method returns an instance of Author whereas the filter() methods returns a QuerySet object.

Let’s see what happens, if get() method encounters multiple records.

Here the get() method raises a MultipleObjectsReturned exception because there are multiple objects in the database that matches the given parameter.

Similarly, if you try to access an object which does not exist then the get() method will raise a DoesNotExist exception.

Ordering Results

To order result we use order_by() method, just like filter() it also returns a QuerySetobject. It accepts field names that you want to sort by as positional arguments.

This code retrieves all the Author objects ordered by id in ascending order. The SQL equivalent of the query is:

Here is another example, in which we first filter the result and sort it by name in ascending order.

The SQL equivalent of the query is:

To reverse the sorting ordering add minus(-) sign before the field name like this:

The SQL equivalent of the query is:

You can also sort the result by multiple fields like this.

This query sorts the result first by name in ascending and then by email in descending order

Selecting the Fields

When you query a database like this:

It returns data from all the fields (columns). What if we want data only from one or two fields ? The objects manager provides a values_list() method for this job. The values_list() method accepts one or more field names from where we want the data and returns a QuerySet. If you don’t pass any values to values_list() method, then the data from all the fields will be returned. For example:

Notice that the values_list() method returns a QuerySet where each element is a tuple. And the tuple only contains data from the fields which we have specified in the values_list() method.

Here is another example:

The objects manager also provides an identical method called values() which works exactly like values_list() but it returns a QuerySet where each element is a dictionary instead of a tuple.

Slicing Results

You can use Python list slicing syntax ([start:end]) to limit your QuerySet object to a certain number of results.

Example 1:

This query sorts the results by id in ascending order and then returns only the first object from the QuerySet. The SQL equivalent of the query is:

Example 2:

This query sorts the results by id in descending order and returns the first three objects from the QuerySet. This code roughly translates to SQL as follows:

Example 3:

This query returns objects from index 2 to 5. The SQL equivalent of the query is as follows:

Unfortunately, we can’t use negative indexes to slice the queryset.

Complex Query with Q objects

We have already seen that when we pass multiple keyword arguments to look up functions (i.e. filter(), exclude() or get() ), they are ANDed together. There will be times when you want to combine two or more conditions using OR operator instead of AND operator. This is where Q objects come into play.

A Q object is just a collection of keyword arguments, that you would normally pass to look up function (filter(), exclude() or get() method). For example:

This Q object encapsulates a single keyword argument. But we can pass as many keyword arguments as we want.

Once we have created a condition using Q object, we can reuse it multiple times in our code without recreating it over and over again.

Note that in the preceding example multiple keyword arguments passed to Q() constructor are ANDed together. That means the following two queries are equivalent.

The SQL equivalent of the query is:

We can combine Q objects using & (bitwise AND) and | (bitwise OR) operators. When we do so, a new Q object is created. The & and | operators allows us to create SQL queries with AND or OR condition respectively. For example:

This query returns all the objects whose name field is either tom or jerry. The SQL equivalent of the query is:

We can pass multiple Q objects to the lookup functions (e.g. filter(), exclude(), get() etc) as position arguments. If we do so, the Q objects will be ANDed together. For example:

The SQL equivalent of the query is:

Finally, we can also mix keyword arguments with Q objects while calling the lookup function. In doing so, remember that all the arguments to the lookup function will be ANDed together and all the Q objects must appear before any keyword arguments. That means the following is a valid query:

But the next one is not.

Updating Multiple Objects

Recall that one way to update an object is to call save() method after updating it’s attributes. For example:

The objects manager provides a method called update() to update one or multiple records in one step. Just like filter() method it accepts one or more keyword arguments. If the update was successful it returns the number of rows updated.

This query modifies the active and name fields of all the authors whose primary key is greater than 3.

This SQL equivalent of the query is:

Here is another example which modifies the active attribute of all objects to False.

The query is equivalent to the following:

The SQL equivalent of the above query is:

Deleting records

As discussed in earlier in this lesson, we can use model’s delete() method to delete an object from the database. For example:

To delete multiple records at once use delete() method provided by the QuerySet object. For example:

You should now have a solid understanding of Django ORM. In the next lesson, we will discuss how to access data from related tables using Django ORM.

Leave a Comment