Search code examples
djangodjango-rest-frameworkdjango-filter

Django-Filter: Search within an ArrayField with an Array?


I have an all_positions datapoint that uses an arrayField. So some example data looks like:

all_positions: ["C", "1B"],
all_positions: ["RP", "CP"],
all_positions: ["CP"],

I'd like to be able to make a request similar to /api/player-profiles/?all_positions=RP,CP and return the second and third examples. Essentially, I want to return all players that have ANY of the positions passed into the URL in their all_positions data.

I've read about overlap, but not sure how I would integrate that into my django-rest filters. Here is what the filter currently looks like:

class PlayerProfileFilter(django_filters.FilterSet):
    all_positions = CharInFilter(field_name='all_positions', lookup_expr='contains')

Solution

  • Just change the lookup filter in lookup_expr from contains to overlap:

    class PlayerProfileFilter(django_filters.FilterSet):
           all_positions = CharInFilter(field_name='all_positions', lookup_expr='overlap')