Django-filter ‘__in’ lookup

I am using django-rest-framework with, 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


to find books with id 1, 2 or 3

Best answer

The question is discussed in this issue:

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: