Django ORM Basics Part 2

In the previous lesson, we have covered all the basics of interacting with the database using Django ORM. We have created, modified and deleted many objects. The type of the objects we have handled till now were simple objects that can exist on their own. In this lesson, we will learn how to insert and access related data, but first, we will populate some data in our tables.

If you are following lessons closely, at this point, all the tables of djangobin app should be empty. Before we proceed, let’s add some Author and Language objects to djangobin_author and djangobin_language tables, respectively. Open Django shell by executing the shell command and import all the models from the djangobin app.

Copy and paste the following code into the Django shell to create some authors and languages.

Let’s now shift our attention to the Snippet model. Here is how the Snippet model is defined:


And this is how djangobin_snippet table looks like:

The Snippet model has two one-to-many relationships. The first with the Author model and second with the Language model.

The data for one-to-many relationships will be stored in the djangobin_snippet table. Furthermore, the author and language fields of the Snippet model do not accept NULL values, as a result, a Snippet object must be associated with an Author and a Language object. Trying to create Snippet object without an Author or Language object will throw an IntegrityError exception.

The Snippet model also has a many-to-many relationship with the Tag model. But since the data for a many-to-many relationship is stored in a separate table (djangobin_snippet_tags), we are not required to provide this data at the time of creating Snippet object. Once we have created a Snippet object, we can add tags to it later. We will see how to do that later in this chapter.

Let’s try creating a Snippet object without providing an author and language and see what happens:

As expected, calling save() method raises an exception of type IntegrityError. You would get the same exception, if you try to create a Snippet object using the create() method of the objects manager.

The error is telling us that the author_id column has NOT NULL constraint on it. Consequently, It can’t accept NULL values.

The reason why we are getting IntegrityError on author_id column instead of language_id column is that the author_id appears before the language_id column in the djangobin_snippet table.

We can allow author field to accept NULL values by passing null=True to the field constructor in the model class. For now, there is no reason to do that.

Okay, let’s try creating Snippet object again, but this time we will provide an Author and a Language object.

As you can see, this time operation succeeded. Instead of calling Snippet() constructor you could also use create() method of the objects manager to create a Snippet object.

We can now use s1 or s2 variable to get the information about the Snippet object as well as about the Author and Language object to which it belongs to using the dot(.) operator.

Notice how we were able to access data stored in different tables without writing SQL JOIN query. That’s the power of the Django ORM.

Instead of passing Author object while creating Snippet object, you could also pass the primary key of the author, but then you would have to assign it to the author_id keyword argument instead of author. In the same way, we can pass Language object’s primary key to the language_id keyword argument.

Before we visit next section, let’s add some Tag objects to our database.

Additional Managers

The objects is not the only the manager available in Django. It turns out that when dealing with many-to-many relationship Django uses a manager called related manager to connect data. In the Snippet model tags field is one such manager. You can verify this by typing the following code in the Django shell.

As tags is a manager you can use all manager methods on it that we have learned in the lesson Django ORM Basics Part 1. For example, to view all the tags associated with the s1 and s2 posts type the following code:

Currently, snippet s1 and s2 are not associated with any tags that’s why an empty QuerySet is returned.

So how do we add tags to existing Snippet objects?

All relationship managers come with add() method which can be used to connect objects.

Now snippet s1 is associated with django tag. The preceding code adds the following record in the djangobin_snippet_tags table.

You can also associate multiple tags with a Snippet object by passing multiple arguments to the add() method.

Reverse Access

When you define relationships in the model class using fields like ForeignKey, ManyToManyField etc. Every instance of that model will have attributes to access related objects. For example, given a Snippet object s1, we can access its author using, its language using s1.language, and its tags using s1.tags.

But, How do we access data other way around? Simply put, How do we access snippets from an Author instance or Tag instance?

Django automatically adds a relation manager of the form <related_model>_set on the other side of the relationship. More Concretely, given a Author object a1, the snippets associated with this author is given by a1.snippet_set. The snippets_set attribute is an instance of type ManyRelatedManager, which inherits from django.db.models.manager.Manager, as a result, most of the manager methods we discussed in the chapter Django ORM basics Part 1 are available to it. For example:

Similarly, given a Tag instance t1, the snippets associated with this tag is given by t1.snippet_set.

If for some reason <related_model>_set attribute doesn’t appear to be intuitive or readable. We can change it by passing related_name parameter to the ForeignKey or ManyToManyField constructor in the model class. For example:

This code will change the relation name from snippet_set to snippets for Author and Tag instance. Given a Tag instance t1, we can now access associated snippets with t1.snippets. Similarly, given an Author instance a1, we can access associated snippets with a1.snippets.

Lookups Spanning Relationship

Up until now, keyword arguments (with or without lookups) we have been passing to the lookup functions (e.g. filter(), exclude(), get() etc; ) were restricted to the model class we are currently operating on.

It turns out that we can also pass the field name of the related model class to lookup functions. To do so, type model name in lower case, followed by two underscores, which is then followed by the field name. Here is the general format:

This spanning can be deep as you would like. Further, you can also use all the lookups we have learned in the lesson Django ORM Basics Part 1. This technique reduces the ad-hoc queries required to perform a given task. For example, let’s say we want to find snippets only from authors whose name ends with om. Here is the long way to find all such snippets.

Using lookups that can span relationship, we can code preceding query in a single line.

This technique works in both directions. For example, the following query retrieves all the authors who have created snippets in the year 2018.

Notice that the preceding query returns three instances of the same Author, this is because in my SQLite database tom has created three snippets. To filter out the duplicate result we can use distinct() method. The distinct() method returns a QuerySet after removing all the duplicates.

get_object_or_404() function

Most of the time our views function goes like this:

  1. Code try and except block.
  2. Query the database in the try block.
  3. If an exception is thrown, catch the exception in the except block and show a 404 page.

This pattern is so common that Django a provides a shortcurt function called get_object_or_404(). Its syntax is:

The klass can be a model, a manager or a queryset.

The **kwargs represents all keyword arguments as well as the lookup parameters that we have been using with the lookup functions ( get(), filter(), exclude() etc).

On success, it returns a single object of the given model, if it can’t find any records then it raises a Http404 exception.

Internally this method calls get() method of the objects manager, so you must always use this method to get a single object.

To use get_object_or_404() first import it from django.shortcuts using the following code.

The following examples shows how to use get_object_or_404() function with models, queryset and managers. It also shows that when a matching record is not found, get_object_or_404() raises a Http404 exception.

Example 1: where klass is model

This code is equivalent to:

Example 2: where klass is queryset

Example 3: where klass is a manager

The get_list_or_404() method

The get_list_or_404() works just like get_object_or_404() function, but instead of returning a single model instance, it returns a Queryset. If no matching results found, it raises a Http404 exception.

Leave a Comment