Alex Cuadra
Alex Cuadra

Reputation: 97

Django filter by brand

im making an ecommerce website with django and im having problems with the filter, I want to show all the brands that I choose. Here is the view:

marca = request.GET.get('marca')

if marca == 'marca':
    products = products.filter (brand__name = marca)

marca is Brand.

here is the template:

{% for brand in q %}
                <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="{{brand.brand}}" name="marca" value="{{brand.brand}}" {% if marca == '{{brand.brand}}' %} checked="checked" {%endif%}>
                    <label class="custom-control-label" for="{{brand.brand}}">{{brand.brand}}</label>
                    </div>
                {% endfor %}

okay so, its showing me with the filter, but only the last one that I checked. If i check 2 brands, it only showing up the last one. So pls i need some help with this:(

Upvotes: 1

Views: 131

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477200

This is the expected behavior of the .get(…) method [Django-doc]. You can use .getlist(…) method [Django-doc] to obtain the list of all selected brands:

products = products.filter(brand__name__in=request.GET.getlist('marca'))

You can work with the __in lookup [Django-doc] to check if the name is in the list of brands.

It is however odd that you check marca == 'marca'. This would only filter in case that the value of marca is the string marca.

Upvotes: 1

Related Questions