Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use django-filters to filter a field by a list of inputs

I have a list of objects that have a country code associated with them, I would like to write a FilterSet class that can receive a list of codes ie. ['US', 'CA'] and will return a list of the objects that have the country code column set to either of those values.

It doesn't seem like filtersets may be able to do this for me, but its seems like a relatively common requirement? I was thinking maybe it's something like __in for the filterset field.

Any help is much appreciated

like image 644
Dash Winterson Avatar asked Jan 23 '26 23:01

Dash Winterson


1 Answers

Filterset can do this using BaseInFilter. Example:

class CharInFilter(BaseInFilter, CharFilter):
    pass


class YourFilterSet(FilterSet):
    code = CharInFilter(field_name='code', lookup_expr='in')

    class Meta:
        model = ModelClass
like image 183
Mahrus Khomaini Avatar answered Jan 26 '26 13:01

Mahrus Khomaini