Creating a relational category model
In our previous recipe, we created a simple product model that had a couple of fields. However, in practice, applications are much more complex and have various relationships among their tables. These relationships can be one-to-one, one-to-many, many-to-one, or many-to-many. We will try to understand some of them in this recipe with the help of an example.
How to do it…
Let's say we want to have product categories where each category can have multiple products, but each product should have at least one category. Let's do this by modifying some files from the preceding application. We will make modifications to both models and views. In models, we will add a Category
model, and in views, we will add new methods to handle category-related calls and also modify the existing methods to accommodate the newly added feature.
First, we will modify our models.py
file to add the Category
model and some modifications to the Product
model:
from my_app...