如何从产品中获取类别?Django

huangapple go评论104阅读模式
英文:

How to get Category from Product? Django

问题

我试图创建一个搜索栏,用户可以选择类别并输入产品名称。这样我就可以显示所有与用户在文本输入中输入的产品名称匹配的该类别中的产品。

所以我有 Category -> Subcategory -> Product。有没有办法从 Product 模型中获取 Category 对象?(我在产品模型中没有类别字段)

以下是我的 models.py 文件:

  1. # models.py
  2. class Category(models.Model):
  3. name = models.CharField(max_length=100, null=True, blank=True)
  4. created = models.DateTimeField(auto_now_add=True)
  5. class Meta:
  6. verbose_name_plural = 'Categories'
  7. def __str__(self):
  8. return self.name
  9. class Subcategory(models.Model):
  10. category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='subcategories')
  11. name = models.CharField(max_length=200, null=True, blank=True)
  12. created = models.DateTimeField(auto_now_add=True)
  13. top5 = models.BooleanField(default=False, null=True, blank=True)
  14. featured = models.BooleanField(default=False, null=True, blank=True)
  15. class Meta:
  16. verbose_name_plural = 'Subcategories'
  17. def __str__(self):
  18. return self.name
  19. class Product(models.Model):
  20. name = models.CharField(max_length=200, null=True, blank=True)
  21. subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_NULL, null=True, related_name='products')
  22. image = models.ImageField(null=True, blank=True, upload_to='products/')
  23. price_old = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True)
  24. price_new = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True)
  25. description = models.TextField()
  26. created = models.DateTimeField(auto_now_add=True)
  27. def __str__(self):
  28. return self.name

正如您所看到的,我尝试创建一个属性来获取类别,但现在我在筛选共享相同类别的产品方面遇到了困难。

以下是我的 views.py 文件:

  1. def search_products(request):
  2. q = request.GET.get('q') if request.GET.get('q') is not None else ''
  3. category = Category.objects.get(name=request.GET['category'])
  4. products = Product.objects.filter(name__icontains=q, subcategory__category=category) # <-- 这一行
  5. context = {'products': products, 'q': q}
  6. return render(request, 'search_products.html', context)

如果您有任何想法,我会非常高兴听到您的建议!

英文:

I'm trying to create a search bar where user can choose Category and write product name. So I can display all products in that category where the name of product matches with what he wrote in text input.

So I have Category -> Subcategory -> Product. Is there any way to get Category object from Product model? (I don't have field for category in product model)

Here is my models.py file:

  1. # models.py
  2. class Category(models.Model):
  3. name = models.CharField(max_length=100, null=True, blank=True)
  4. created = models.DateTimeField(auto_now_add=True)
  5. class Meta:
  6. verbose_name_plural = &#39;Categories&#39;
  7. def __str__(self):
  8. return self.name
  9. class Subcategory(models.Model):
  10. category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name=&#39;subcategories&#39;)
  11. name = models.CharField(max_length=200, null=True, blank=True)
  12. created = models.DateTimeField(auto_now_add=True)
  13. top5 = models.BooleanField(default=False, null=True, blank=True)
  14. featured = models.BooleanField(default=False, null=True, blank=True)
  15. class Meta:
  16. verbose_name_plural = &#39;Subcategories&#39;
  17. def __str__(self):
  18. return self.name
  19. class Product(models.Model):
  20. name = models.CharField(max_length=200, null=True, blank=True)
  21. subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_NULL, null=True, related_name=&#39;products&#39;)
  22. image = models.ImageField(null=True, blank=True, upload_to=&#39;products/&#39;)
  23. price_old = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True)
  24. price_new = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True)
  25. description = models.TextField()
  26. created = models.DateTimeField(auto_now_add=True)
  27. def __str__(self):
  28. return self.name
  29. # @property
  30. # def category(self):
  31. # return self.subcategory.category

Here as you can see I tried to create a property to get the category, but now I'm struggling to filter products that share the same category

Here is my views.py file:

  1. def search_products(request):
  2. q = request.GET.get(&#39;q&#39;) if request.GET.get(&#39;q&#39;) != None else &#39;&#39;
  3. category = Category.objects.get(name=request.GET[&#39;category&#39;])
  4. products = Product.objects.filter(name__icontains=q, category=category) &lt;-- This line
  5. context = {&#39;products&#39;:products, &#39;q&#39;:q}
  6. return render(request, &#39;search_products.html&#39;, context)

If you have any ideas, I would be really glad to hear you!

答案1

得分: 0

是的。由于您的 Product 模型有一个外键指向 Subcategory,而 Subcategory 有一个外键指向 Category,您可以在模板中执行以下操作:

  1. {% for product in products %}
  2. 分类{{ product.subcategory.category }}
  3. 产品{{ product }}</div>
  4. {% endfor %}

要进行筛选,您应该使用双下划线 (__) 语法:

  1. products = Product.objects.filter(
  2. name__icontains=q,
  3. subcategory__category=category
  4. )
英文:

Yes. Since your Product model have a foreign key to Subcategory, and Subcategory has a foreign key to Category, you can do the following in your template:

  1. {% for product in products %}
  2. Category: {{ product.subcategory.category }}
  3. Product: {{ product }}&lt;/div&gt;
  4. {% endfor %}

To filter them, you should use the double underscore (__) syntax:

  1. products = Product.objects.filter(
  2. name__icontains=q,
  3. subcategory__category=category
  4. )

huangapple
  • 本文由 发表于 2023年6月22日 11:57:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定