Many-to-Many Relationships by Example

Many-to-Many Relationships by Example
Author: Mohammad Amaan Abbasi | Aug. 24, 2018
In this tutorial, I will show you, how I build a category model for my Django blog, that filters out posts based on a category, a user clicks on.

The only thing you need to understand are "Many-To-Many" relationships.

What is a Many-To-Many Relationship?

Let's say we have two models one of books, and the other of authors - each book can have one or more authors, and each author may have written multiple books.
We have many books related to many authors. This is kind of relationship is called Many-To-Many relationship.

Here is how we can visualize the relationship:


This is how my models look-like. For simplicity, I have removed some of the fields.


A question might arise, In which model, Category or Post should one put ManyToMany field ? The answer is, it doesn't matter. However, for your practice try to add the ManyToMany field to the other model.

Run migrations and add Post and Category to the Admin panel.

python makemigrations

python migrate

Adding some data to work with:

django-admin manytomany

Click on the top right icon to Add a category django-admin2 manytomany

Finally, Add posts to a Category. django-admin3 manytomany

Next, we have to add URL pattern for the category, so go to and add the following line in urlpatterns list.

Now, how will this actually work?

Step 1 : Query for the Category object.

Step 2 : Get the posts for that query.

Here, the post_category view function takes an argument slug, which is the category name. Next line, checks whether the object exists. If the object exists than from that object it queries the related posts and pass it to the template.



We learnt about Many-To-Many relationships. We used this concept to create a category section for a blog.