I was doing the project on Django to get into it more deeply. I have a problem in the model part. There are models; Company
, Product
, Category
. Company
is simply the introduction part. Product
is about what product a company has and its divided into category which is ManyToManyField
.
I have list all the categories in a page where if certain category is clicked then the list of companies that has product of that category should be filtered. But I don't know how to access it.
Here is my model
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True)
class Product(models.Model):
name = models.CharField(max_length=200, unique=True, blank=False, null=False)
company = models.ForeignKey('Company', related_name='products', blank=True, null=True, on_delete=models.SET_NULL)
website = models.URLField(unique=True)
slug = models.SlugField(unique=True)
categories = models.ManyToManyField(Category, related_name='products')
class Company(models.Model):
name = models.CharField(max_length=200, unique=True, blank=False, null=False)
slug = models.SlugField(unique=True)
description = models.CharField(max_length=400)
editor = models.ForeignKey(User, related_name='company')
# product = models.ForeignKey(Product, related_name='company')
You can apply the filter:
where
category_slug
it is the value of your current selectCategory.slug
details:
1) if we need to get
Category
2) if we need get all
Product
in this categoryor add double underscore to many2many models field name
3) if need get
Company
for the product_list, filter by related_name of related modelProduct
in the field FK on theCompany
company = models.ForeignKey('Company', related_name='products'
or by category instance
or finaly by category slug value