I want to filter my model with django-filter. It works fine if I filter by one id like:
http://localhost:8000/accommodations?accommodationType_id=1
But I don't know how I can filter by multiple ids like.
http://localhost:8000/accommodations?accommodationType_id=1,2
My actual ViewSet
looks like this:
class AccommodationViewSet(viewsets.ReadOnlyModelViewSet):
"""
REST API endpoint for 'accommodation' resource
"""
queryset = Accommodation.objects.all()
serializer_class = AccommodationSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('accommodationType_id', 'name')
I hope there is a solution.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.
I know it is an old question, but might be worth it to give an updated answer.
Django-filter contributors have added a field called BaseInFilter
which you can combine with other filters to validate the content.
See the docs: https://django-filter.readthedocs.io/en/latest/ref/filters.html#baseinfilter
For example, this would work in your case:
from django_filters import rest_framework as filters
class NumberInFilter(filters.BaseInFilter, filters.NumberFilter):
pass
class AccommodationFilter(filters.FilterSet):
accommodationType_id_in = NumberInFilter(field_name='accommodationType_id', lookup_expr='in')
class Meta:
model = Accommodation
fields = ['accommodationType_id_in', ]
Then you would be able to filter by a list of ids: http://localhost:8000/accommodations?accommodationType_id_in=1,2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With