Dash Winterson
Dash Winterson

Reputation: 1295

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

Upvotes: 3

Views: 1292

Answers (1)

Mahrus Khomaini
Mahrus Khomaini

Reputation: 814

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

Upvotes: 6

Related Questions