Django-filter: Filtering ArrayField

Created on 24 Aug 2016  ·  4Comments  ·  Source: carltongibson/django-filter

Is it possible to filter fields defined in django.contrib.postgres.fields like ArrayField?

Most helpful comment

django-filter currently doesn't have any filters compatible with the postgres contrib fields - you would need to create your own. It will be more or less difficult depending on what you're trying to do. Supporting the custom lookups for ArrayField would be fairly trivial:

class CharArrayFilter(filters.BaseCSVFilter, filters.CharFilter):
     pass

class MyFilterSet(filters.FilterSet):
    tags__contains = CharArrayFilter(name='tags', lookup_expr='contains')

    class Meta:
        model = SomethingTaggable
GET http://localhost/api/something-taggable?tags__contains=a,b,c

The above filter will validate the comma-separated inputs and return a list of cleaned values, which is suitable for the underlying .filter() call.

On the other hand, it's a little more complicated to handle the index and slice transforms, which are unstructured and have a theoretically infinite amount of combinations.

All 4 comments

django-filter currently doesn't have any filters compatible with the postgres contrib fields - you would need to create your own. It will be more or less difficult depending on what you're trying to do. Supporting the custom lookups for ArrayField would be fairly trivial:

class CharArrayFilter(filters.BaseCSVFilter, filters.CharFilter):
     pass

class MyFilterSet(filters.FilterSet):
    tags__contains = CharArrayFilter(name='tags', lookup_expr='contains')

    class Meta:
        model = SomethingTaggable
GET http://localhost/api/something-taggable?tags__contains=a,b,c

The above filter will validate the comma-separated inputs and return a list of cleaned values, which is suitable for the underlying .filter() call.

On the other hand, it's a little more complicated to handle the index and slice transforms, which are unstructured and have a theoretically infinite amount of combinations.

Thanks for info.

I'm going to close this as Out of Scope for the moment. Happy to consider documented, tested pull requests. We may have capacity to reconsider in the future.

Update:
Parameter name has been renamed to field_name so the MyFilterSet should look like:

class MyFilterSet(filters.FilterSet):
    tags__contains = CharArrayFilter(field_name='tags', lookup_expr='contains')

    class Meta:
        model = SomethingTaggable
Was this page helpful?
0 / 5 - 0 ratings