Django-filter | Boolean fields

P. Rodoreda picture P. Rodoreda · Dec 27, 2017 · Viewed 9.7k times · Source

I'm using django-filter package and I have many boolean fields. Is there a way to filter only when field is True? And show all other posibilities?

For example if I have 3 fields: True, False, False... Render objects that have 1st field equal True but doesn't matter about de rest, don't consider it False.

model.py

class Product(models.Model):
    name = models.CharField(max_length=15)
    is_dangerous = models.BooleanField()
    is_secret = models.BooleanField()
    is_active = models.BooleanField()

filters.py

class SearchFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains')
    class Meta:
        model = Product
        fields = ['name', 'is_dangerous', 'is_secret', 'is_active',]
        filter_overrides = {
            models.BooleanField: {
                'filter_class': django_filters.BooleanFilter,
                'extra': lambda f: {
                    'widget': forms.CheckboxInput,
                },
            },
        }

urls.py

url(r'^products/$', views.products, name='products')

When I enter to products/ for the first time, I only see products that has all boolean fields = False and I want to see ALL products.

Answer

Mathyou picture Mathyou · Dec 27, 2017

You don't need all of that filter stuff. To filter models based on the value of a BooleanField all you need is

dangerous_products = Product.objects.filter(is_dangerous=True)

This will return a QuerySet of all model instances with is_dangerous set to True.

You can then pass this variable to your template and display the information like this

{% for product in dangerous_product %}
    <!-- Put whatever way you want to display each product in here. EX:-->
    <h1>{{ product.name }}</h1>
{% endfor %}

The above template will display the name of every product with is_dangerous set to True.