Django-filter ‘__in’ lookup

I am using django-rest-framework with https://github.com/alex/django-filter/, but question is mostly about django-filter. I can’t understand how to use filters with “__in” lookup.

For example i have model:

class Book(models.Model):
   name = models.CharField(max_length=100)

class BookView(viewsets.ReadOnlyModelViewSet):
   serializer_class = BookSerializer()
   model = Book
   filter_fields = ('id', 'name')

And i can’t use url like this

/v1/books/?id__in=1,2,3

to find books with id 1, 2 or 3

Best answer

The question is discussed in this issue: https://github.com/alex/django-filter/issues/137#issuecomment-77697870

The suggested solution would be to create a custom filter as follows:

from django_filters import Filter
from django_filters.fields import Lookup

from .models import Product

class ListFilter(Filter):
    def filter(self, qs, value):
        value_list = value.split(u',')
        return super(ListFilter, self).filter(qs, Lookup(value_list, 'in'))

class ProductFilterSet(django_filters.FilterSet):
    id = ListFilter(name='id')

    class Meta:
        model = Product
        fields = ['id']

And the you can write the following:

products/?id=7,8,9