Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering Django REST framework using IN operator

I basically need something like /?status=[active,processed] or /?status=active,processed

My current setting is: 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',) and it's only filtering one value correctly (/?status=active)

like image 450
Adam Silver Avatar asked Mar 27 '16 18:03

Adam Silver


1 Answers

I think there is no inbuilt functionality for that. But you can implement a custom filter to do that. This custom filter you can use in your filterset.

import django_filters as df

class InListFilter(df.Filter):
    """
    Expects a comma separated list
    filters values in list
    """
    def filter(self, qs, value):
        if value:
            return qs.filter(**{self.name+'__in': value.split(',')})
        return qs

class MyFilterSet(df.FilterSet):
    status = InListFilter(name='status')
like image 58
ilse2005 Avatar answered Sep 30 '22 01:09

ilse2005