Accessing Related Data Using Django ORM

In the previous lesson, we have covered all the basic stuff needed to interact with the database using Django ORM. We have created, modified and deleted many objects. The type of the objects we 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 before we do that we will populate some data in Category, Post and Tag‘s table first.

If you are following these lessons closely your Author table i.e blog_author should be empty. Before we proceed, let’s add some Author objects to the blog_author table. Open Django shell by executing the shell command and import all necessary models from the blog app.

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

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


And this is how blog_category table looks like:

blog_category table

An important point to notice here is that Category model has a one-to-many relationship with the Author‘s model. As a result, a Category object must be associated with an Author object.

Let’s try creating a Category object and see what happens:

Calling save() method raises an exception of type IntegrityError. You would get the same exception, even if you try to create a Category object using the create() method of the objects manager.

So what’s the problem?

The problem is we are trying to create a Category object without an Author.

Okay, let’s try creating Category object one more time, but this time we will provide an Author.

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

We can now use c1 variable to get the information about the Category object as well as Author who created this object using the dot(.) operator.

Notice that in the last two commands we are accessing data stored in a different table i.e blog_author without writing SQL join query. That’s the power of the Django ORM.

Instead of passing Author object wile creating Category object, you could also pass primary key of the author, but then you would have to assign it to the author_id keyword argument instead of author.

Similarly, you can create Tag objects as follows:

Now we know how to create Category and Tag objects let’s shift our attention to the Post model. This is how the Post model is defined.


A Post object has following relationships:

  1. A one-to-many relationship between Post and Category object.
  2. A one-to-many relationship between Post and Author object.
  3. A many-to-many relationship between Post and Tag object.

This is how Post table (i.e blog_post) looks like:

blog_post table

As you can see to create a Post object we have to provide an Author and a Category.

Let’s create some Post objects.

Note that while creating Post object we are not passing any tags to the create() method. This is because a Post object has a many-to-many relationship between Tag object. As a result, the relationship between them will be stored in a different table (blog_post_tags in this case). Once a Post object is saved into the database, we can add tags to it later as you will see.

The variables a1 and c1 must point to a valid Author and Category object respectively otherwise you will get an error.

This is how a Post object looks like in the blog_post table.

post object inside database

Just as with Category or Tag object, we can use a Post object to find any relevant information about the author and category associated with it.

Let’s finish this section by creating another Post object.

More 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 to connect data. In the Post 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.

To view all the tags associated with the p1 and p2 posts type the following code:

Currently, posts p1 and p2 are not associated with any tags that’s why an empty QuerySet object is returned.

So how do we add tags to existing Post objects?

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

Now post p2 is associated with django tag. The above command adds the following record in the blog_post_tags table.

blog_post_tags table

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

We know that once we have a Post object we can find all the information related to it like category, author, tags etc. But, How do we access data another way around? Simply put how do we find all post related to a particular tag or all the post published by a particular author?

Let p, a, c, t be a Post, Author, Category and Tag objects respectively, then

  • All the posts published by author a is given by – a.post_set.all().
  • Author of post p is given by –
  • All the posts published under category c is given by – c.post_set.all().
  • Category of post p is given by –
  • All the posts filed under tag t is given by – t.post_set.all().
  • All tags related to post p is given by – p.tags.all().

In case you are wondering what is post_set?

The post_set is just another relation manager that Django has created dynamically for you to make database interaction easy. As post_set is a manager you can use all the manager methods on it. You can verify this by executing the following code.

Creating objects the other way around

So far we have been creating objects either by Model’s constructor method i.e Post(), Category() etc; or by using create() method of the objects manager. The other way to create objects is to use related model class and then use the manager’s create() method on it. For example, Post and Category model have one-to-many relationship between them, so instead of creating Post object using Post constructor (i.e Post()) or objects manager’s create() method, we can use Category object to create a Post object. Here are are some examples:

Notice that we are not passing an object of type Category while creating Post object because we are calling create() method on the object of type Category.

Similarly, you can create Post object from a Tag object or Author object.

Fetching records using related fields

Let’s say you want to find all the posts from the category 'java'. Here is the one way to find all such posts.

Up until now, keyword arguments we have been passing to the filter() method only belongs to the model on which it is called. It turns out that if models are related then we can also pass related field names to the filter() method using the following format.

That’s double underscore (__) between model and field.

Using this technique we can achieve the same result as above in one line.

Notice that category__name consists of two underscores.

Similarly, we can find all the post belongs to the author "tom".

We can also apply lookups to category__name, author__name.

2 thoughts on “Accessing Related Data Using Django ORM

  1. just to add that all the tags created by author a is a.tag_set.all() and similarly all categories created by author a is given by a.category_set.all()

Leave a Comment

%d bloggers like this: