我有两个模型 - “产品”和“类别”,每个产品都可以添加到现有类别中。我正在尝试找到一种方法来呈现包含按类别过滤的产品的页面。目前,我通过在模板中手动过滤每个类别来完成此操作:{% for instance in object_list %} {% if instance.category.categoryname == "Statues" %} {{ instance.name }} {{ instance.description }} {{ instance.price }} {% endif %}{% endfor %}我对每个类别(“绘画”、“珠宝”等)都有相同的模板,并更改了每个模板中的条件。URL“../Statues”指向预先存在的模板有什么办法可以更轻松地做到这一点吗?我希望 从 URL 导入条件{% if instance.category.categoryname == "Statues" %} 。因此,当您访问“../Jewelry”时,模板将从 URL 导入“Jewelry”并相应地过滤内容。models.pyclass Category(models.Model): categoryname = models.CharField(max_length=20) description = models.CharField(max_length=200, blank=True, null=True) #To make in name, not objXXX def __str__(self): return self.categorynameclass Product(models.Model): name = models.CharField(max_length=20) image = models.ImageField(upload_to='static/photos', default='http://placehold.it/700x400') description = models.TextField(max_length=200, blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10) category = models.ForeignKey(Category, on_delete=models.PROTECT, blank=True, null=True) #To make in name, not objXXX def __str__(self): return self.nameurls.pyurlpatterns = [ path('admin/', admin.site.urls), path('<str:categoryname>', category_filter)]view.pydef category_filter(request, categoryname): queryset = Product.objects.all() context = {"object_list": queryset} return render(request, "category_filter.html", context)类别选择模板:{% for instance in category_list %}<a href="{{ instance.categoryname }}" class="list-group-item">{{ instance.categoryname }}</a>{% endfor %}
1 回答
杨__羊羊
TA贡献1943条经验 获得超7个赞
这可能太简单了......您可以在视图中应用过滤器并基于此发送查询集:
def category_filter(request, categoryname):
category=Category.objects.get(categoryname=categoryname)
queryset = Product.objects.filter(category=category)
context = {"product_list": queryset}
return render(request, "category_filter.html", context)
添加回答
举报
0/150
提交
取消