The only thing you need to understand are "Many-To-Many" relationships.
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
Category to the Admin panel.
python manage.py makemigrations
python manage.py migrate
Adding some data to work with:
Click on the top right icon to Add a category
Finally, Add posts to a Category.
Next, we have to add URL pattern for the category, so go to urls.py 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.