Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to do an `in` `lookup_type` through the django-filter URL parser?

I'm using django-filter with django-rest-framework and I'm trying to instantiate a filter that accepts lists of numbers for filtering the query set down

class MyFilter(django_filters.FilterSet):   
    ids = django_filters.NumberFilter(name='id',lookup_type='in')
    class Meta:
        model = MyModel
        fields = ('ids',)

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer
    filter_class = MyFilter

If I pass in a comma separated list of integers, the filter is ignored altogether.

If I pass in a single integer, it gets through django-filter into django's form validator and complains:

'Decimal' object is not iterable

Is there a way to create a django-filter object which can handle a list of integers and properly filter down the queryset?

like image 437
Ross Rogers Avatar asked Jun 04 '14 15:06

Ross Rogers


1 Answers

For better or worse, I created a custom filter for this:

class IntegerListFilter(django_filters.Filter):
    def filter(self,qs,value):
        if value not in (None,''):
            integers = [int(v) for v in value.split(',')]
            return qs.filter(**{'%s__%s'%(self.name, self.lookup_type):integers})
        return qs

Which is used like:

class MyFilter(django_filters.FilterSet):   
    ids = IntegerListFilter(name='id',lookup_type='in')
    class Meta:
        model = MyModel
        fields = ('ids',)

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer
    filter_class = MyFilter

Now my interface accepts comma-delimited lists of integers.

like image 87
Ross Rogers Avatar answered Oct 14 '22 12:10

Ross Rogers