[Django]-Django FilterSet AND(?) condition

4👍

You’ll need to create a new filter that handles the name, val pair on a single Food object that is related to a given Component:

class FoodComponentFilter(django_filters.Filter):
    def filter(self, qs, value):
        strs = value.split(',')
        if len(strs) != 2:
            raise Exception
        return qs.filter(
            food_components__in = Component.objects.filter(
                name=strs[0],
                value=float(strs[1])
            )
        )

Instantiate this in the FoodFilter:

class FoodFilter(filters.FilterSet):
   component_food_pair = FoodComponentFilter(name='dummy_field')
   [...]
   class Meta:
        model = Food
        fields = ('component_food_pair',[...])

Then, use it like:

?component_food_pair=Foo,42.0

Leave a comment