首页 > 解决方案 > 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 %}

标签: pythondjangodjango-templates

解决方案


答案可能太简单了......您可以在您的视图中应用过滤器并基于此发送查询集:

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)

推荐阅读