Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-filter | Boolean fields

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.

like image 717
P. Rodoreda Avatar asked Dec 27 '17 15:12

P. Rodoreda


2 Answers

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.

like image 129
Mathyou Avatar answered Oct 11 '22 00:10

Mathyou


For effective boolean filtering, you have to use

from django_filters import rest_framework as filters 
class SearchFilter(filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains')
    class Meta:
        model = Product
        fields = ['name', 'is_dangerous', 'is_secret', 'is_active',]
like image 43
Kwaku Karikari Avatar answered Oct 10 '22 23:10

Kwaku Karikari