首页 > 解决方案 > 我了解复选框可能会传递多个值以进行进一步过滤。如何使用同一列的两个值来过滤表

问题描述

那是我的html文件:

<form action="{% url 'search' %}">
    <div>
<label for="manufacture">Производитель</label><br>
<input type="checkbox" id="manufacture" name="manufacture" value="Samsung">Samsung <br>
<input type="checkbox" id="manufacture" name="manufacture" value="Honor">Honor <br>
<input type="checkbox" id="manufacture" name="manufacture" value="Huawei">Huawei <br>
<input type="checkbox" id="manufacture" name="manufacture" value="Apple">Apple <br>
<input type="checkbox" id="manufacture" name="manufacture" value="Xiaomi">Xiaomi <br>
   </div>
<input type="submit" value="Submit"class="btn btn-primary">
  </form>

那是我的views.py:

def search(request):
queryset_list=Product.objects.order_by('-created')
if 'manufacture' in request.GET: 
    manufacture=request.GET['manufacture']
    if manufacture:
        queryset_list=queryset_list.filter(brand__iexact = manufacture)
 context= {
     products': queryset_list,
 }
 return render (request, 'cart_2/search.html', context)

当我同时检查三星和荣耀时,过滤只给我一个制造商。我想要两个。请帮忙

标签: django-models

解决方案


你想要MultiValuesDict.getlist()__in查找

def search(request):
    qs = Product.objects.order_by('-created')

    manufactures = request.GET.getlist("manufacture", None)
    if manufactures:
        qs = qs.filter(brand__in=manufactures)

    context= {
       'products': qs,
    }
   return render (request, 'cart_2/search.html', context)

此外(不相关但)您当然希望将您的品牌作为一个独特的模型(从产品到品牌的 FK) - 这是非常基本的关系模型规范化,并且有很好的理由这样做。


推荐阅读