Create a filterset with arrayfield

1,587 views
Skip to first unread message

Michele Gatti

unread,
Jun 14, 2017, 5:20:16 AM6/14/17
to django-filter
Hi i have a problem,i use postgreSQL and django.
I have a field in model with arrayField i can't underestand in which way is possible create a filter contain on that field.

Thanks

Carlton Gibson

unread,
Jun 14, 2017, 5:39:40 AM6/14/17
to django-filter
You can query by hand right? See https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/#querying-arrayfield

So first option is (always) to specify a custom `method` — you can use any logic you like there. 

But have you tried specifying `lookup_expr` https://django-filter.readthedocs.io/en/develop/ref/filters.html#lookup-expr — the contrib fields should make that Just Work™. 

If you run into specific issues it'll be easier to say something concrete. 

Michele Gatti

unread,
Jun 14, 2017, 7:00:56 AM6/14/17
to django-filter
i create this filter class 
class PhotoFilter(filters.FilterSet):
    class Meta:
model = Photo
fields = {'brand__id':['exact'],
'mention_language':['exact'],
'user__sex':['exact'],
'mv_comments_count':['gte'],
'mv_likes_count':['gte'],
'mention_tags':['contains']}
When i run the project i recived thi error 
AssertionError: PhotoFilter resolved field 'mention_tags' with 'contains' lookup to an unrecognized field type ArrayField. Try adding an override to 'Meta.filter_overrides'. See: https://django-filter.readthedocs.io/en/develop/ref/filterset.html#customise-filter-generation-with-filter-overrides

but in django-filter there isn't a ArrayFilter to overrides 

Carlton Gibson

unread,
Jun 14, 2017, 8:07:52 AM6/14/17
to django-filter
I think you'd want a CharFilter. Try adding an override for that for ArrayField.

Or better, declare filters explicitly.

Either should work.

📱

Michele Gatti

unread,
Jun 14, 2017, 2:02:14 PM6/14/17
to django-filter
I try this code:
filter_overrides = {
ArrayField: {
'filter_class': filters.CharFilter,
'extra': lambda f: {
'lookup_expr': 'icontains',
},
},
}

and work with one word if i want more than one how can do it?

Carlton Gibson

unread,
Jun 16, 2017, 4:26:04 AM6/16/17
to django-filter
Hi Michele, 

First I'd stop using the dict fields syntax and explicitly declare fields. 

If you're looking to filter for a list of values you can use the CSV filtering...

class CharInFilter(django_filters.BaseInFilter, django_filters.CharFilter):
    pass

class PhotoFilter(django_filters.FilterSet):
    mention_tags = CharInFilter(lookup_expr='icontains')

... or such.



C.

Michele Gatti

unread,
Jun 23, 2017, 10:01:43 AM6/23/17
to django-filter
Thanks i resolved
Reply all
Reply to author
Forward
0 new messages