Skip to content Skip to sidebar Skip to footer

Filter Company Based On Category

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 p

Solution 1:

You can apply the filter:

Company.objects.filter(products__categories__slug=category_slug)

where category_slug it is the value of your current select Category.slug

details:

1) if we need to get Category

cat = Category.objects.get(slug=category_slug)

2) if we need get all Product in this category

 product_list = Product.objects.filter(categories=cat)

or add double underscore to many2many models field name

 product_list = Product.objects.filter(categories__slug=cat)
 #                                               ^^^^

3) if need get Company for the product_list, filter by related_name of related model Product in the field FK on the Company company = models.ForeignKey('Company', related_name='products'

 Company.objects.filter(products__in=product_list)
 #                      ^^^^^^^

or by category instance

 cat = Category.objects.get(slug=category_slug)
 Company.objects.filter(products__categories=cat)

or finaly by category slug value

Company.objects.filter(products__categories__slug=category_slug)

Post a Comment for "Filter Company Based On Category"