Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use the django-filter package with a list of parameters?

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.

like image 632
abuder Avatar asked Jun 24 '15 14:06

abuder


People also ask

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

Can you filter by property Django?

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.


1 Answers

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

like image 182
Agey Avatar answered Sep 30 '22 02:09

Agey