[Answered ]-Django-filters how to use BooleanFilter to range or else

0👍

Following answers

  1. https://stackoverflow.com/a/77374474/21259369 and
  2. https://stackoverflow.com/a/852481/21259369

I used Multiple Choice Filter and query union Q() with a trick here "queries_set |= query" and i got multiple combined and single selection.

from django.db.models import Q

from django_filters import rest_framework as filters

from apps.products.models import Product


class ProductsFilter(filters.FilterSet):

    percentage_field = filters.MultipleChoiceFilter(
        choices=[
            ("bef50", "<50"),
            ("eq50", "50"),
            ("aft50", ">50"),
        ],
        method="filter_percentage_field",
        label="Choose percentage"
    )

    def filter_percentage_field(self, queryset, name, values):
        request = []
        for value in values:
            if value == "bef50":
                request.append(Q(percentage_field__gt=50))
            elif value == "eq50":
                request.append(Q(percentage_field=50))
            elif value == "aft50":
                request.append(Q(percentage_field__lt=50))

        queries_set = request.pop()
        for query in request:
            queries_set |= query

        return queryset.filter(queries_set)

    class Meta:
        model = Product
        fields = ['percentage_field']
👤Nzr

1👍

AS you mentioned, you can use the ChoiceFilter(...) filter as follows

class ProductFilter(FilterSet):
    percentage_field = django_filters.ChoiceFilter(
        choices=[
            ("type_one", "Type One"),
            ("type_two", "Type Two"),
            ("type_half", "Type Half"),
        ],
        method="filter_percentage_field",
    )

    def filter_percentage_field(self, queryset, name, value):
        if value == "type_one":
            return queryset.filter(percentage_field__gt=50)
        elif value == "type_two":
            return queryset.filter(percentage_field__lt=50)
        elif value == "type_half":
            return queryset.filter(percentage_field=50)
        return queryset

    class Meta:
        model = Product
        fields = ["percentage_field"]

I’ve updated the filtering logic using lt & gt lookup expressions since that makes more sense. Feel free to update the logic in your code as per your business logic.

👤JPG

Leave a comment