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
The documentation for django-filter is sparse. You could try creating a custom filter and specifying the lookup type. It's rather convoluted:
And then modify your view to use the filter class:
You'll then be able to lookup books via their ids (note "__in" not used):
The django-filter provides
BaseInFilter
to be used in conjunction with other filter classes, such asNumberFilter
,CharFilter
. This class only validates that the incoming request iscomma-separated
.So if you're using the Web Browsable API, you can send request as /book/?id__in=1%2C
3 where%2C
is comma.filters.py
views.py
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:
And the you can write the following:
Instead
/v1/books/?id__in=1,2,3
you can use/v1/books/?id=1&id=2&id=3
I have just answered the same question in DjangoFilterBackend with multiple ids
For your case, this should work without having to write any logic.
Now you should be able to filter by a list of ids in your get parameters, such as
/v1/books/?id__in=1,2,3
The django admin site only create urls under the template app_name/model_name/primary_key to edit an instance of the model. It doesn't provide the
__in
filtering through URLS.You have to create a custom view:
And in mytemplate.html:
In urls.py add an entry to this view.
Then try a GET request to your URL with the parameters
?ids=1_2_3