filter company based on category

2019-08-23 03:04发布

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')

1条回答
神经病院院长
2楼-- · 2019-08-23 03:29

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)
查看更多
登录 后发表回答