filter company based on category

六眼飞鱼酱① 提交于 2019-12-24 18:57:40

问题


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:


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)


来源:https://stackoverflow.com/questions/46253328/filter-company-based-on-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!