python - Django 模板 - 过滤内容
问题描述
我有两个模型 - “产品”和“类别”,每个产品都可以添加到现有类别中。我正在尝试找到一种方法来呈现按类别过滤的产品页面。目前我通过在模板中手动过滤每个类别来完成它:
{% 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”并相应地过滤内容。
模型.py
class 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.categoryname
class 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.name
网址.py
urlpatterns = [
path('admin/', admin.site.urls),
path('<str:categoryname>', category_filter)
]
视图.py
def 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 %}
解决方案
答案可能太简单了......您可以在您的视图中应用过滤器并基于此发送查询集:
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)
推荐阅读
- laravel - 如何解决错误 - “提交的 URI 太大!”
- mysql - 如何删除 MySQL 表中的重复行?
- python - 在烧瓶中将数据从类传输到网页
- optimization - 如何在最大化函数中优化 numpy 数组的线性系数?
- c# - 在 Linq 中使用变量引用属性名称
- mongodb - 更新后如何仅返回数组内的更新子文档
- postgresql - 在 Postgresql 上使用 group by 计数
- python - 预测发生时的准确性差
- c# - 读取 excel 文件:来自 c# 的连接错误?
- c# - c# - 如何从数据库中获取等于DataGridView1选定行ID单元格值的ID