首页 > 解决方案 > 在 Django 中按类别过滤产品

问题描述

我的主页上有一个过滤器列表:

<!-- ? Filter -->
<div class="filter border-top border-bottom row">
    <a href="#">
        <img src="{% static 'store/images/bottoms.png' %}" alt="">
    </a>
    <a href="#">
        <img src="{% static 'store/images/outerwear.png' %}" alt="">
    </a>
    <a href="#">
        <img src="{% static 'store/images/tshirt.png' %}" alt="">
    </a>
    <a href="#">
        <img src="{% static 'store/images/shoes.png' %}" alt="">
    </a>
    <a href="#">
        <img src="{% static 'store/images/skateboard.png' %}" alt="">
    </a>

并尝试使用以下内容进行过滤:

class ProductListView(ListView):
    model = Product
    template_name = "store/home.html"

    def get_queryset(self):
        catagory = catagory.objects.filter(catagory)

我可以将单击的图标的类别名称传递给视图以对其进行过滤吗?我也可以将过滤器传回我的主页(那已经列出了所有产品)吗?

这是我的家庭视图:

class ProductListView(ListView):
    model = Product
    template_name = "store/home.html"
    context_object_name='products'
    ordering = ['-date_posted']

将查询集添加到此并将过滤器设置为默认值会更容易吗?任何帮助表示感谢。

标签: pythondjangodjango-filter

解决方案


您的链接应类似于:

<a href="{% url product_filter filter=bottoms %}">
    <img src="{% static 'store/images/bottoms.png' %}" alt="">
</a>

# urls.py
path(r'product/<filter>/', ProductListView.as_view(), name='product_filter')),

然后你只需要在视图中捕获参数,然后过滤列表。


编辑:在评论中添加问题的响应和代码以获得更好的格式。

class ProductListView(ListView): 
    model = Product 
    template_name = "store/filter.html" 
    context_object_name='products' 
    ordering = ['-date_posted'] 

    def get_queryset(self): 
        return Product.objects.filter(catagory__name=self.kwargs['filter']))

推荐阅读