以下是观点:
def all(request):
products = Product.objects.all()
context = {'products': products}
template = 'products/all.html'
return render(request, template, context)
模特:
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(null=True, blank=True)
category = models.ManyToManyField(Category, blank=True)
现在,在模板中,我希望根据类别获取各个领域的帖子。我尝试过:
{% for product in products %}
{% if product.category == "womens-clothin" %}
但它没有用。此外,尝试了观点:
products = Product.objects.filter(category='womens-clothin')
但没有效果。怎么弄清楚这个?
答案 0 :(得分:2)
你不能这样做,
products = Product.objects.filter(category='womens-clothin')
因为类别的类型为ManyToManyField
而不是string
。
首先选择Category对象。像,
some_category = Category.objects.get(category_name="SOMETHING")
然后执行,
products = Product.objects.all().filter(category=some_category)