Django-filter: Contains / icontains filter not working

Created on 16 Jan 2017  ·  4Comments  ·  Source: carltongibson/django-filter

class OrderFilter(django_filters.FilterSet):
    class Meta:
        model = Order
        fields = {
            'status': ['exact',],
            'client': ['icontains',],
        }
class OrderViewset(viewsets.ModelViewSet):
    filter_class = OrderFilter
    permission_classes = ( permissions.IsAuthenticated, )
    serializer_class = OrderSerializer
    queryset = Order.objects.all()
    filter_backends = (
        filters.OrderingFilter,
        filters.SearchFilter,
        filters.DjangoFilterBackend
    )
    ordering_fields = ('added_at', 'status', 'client', 'order_number')
    ordering = ('-added_at',)
class Order(models.Model):
    order_number = models.CharField(max_length=255, default='')
    client = models.CharField(max_length=255, default='')
    status = models.CharField(max_length=255, default='')
    added_at = models.DateTimeField(auto_now_add=True)

Client filter is basically ignored. If I replace icontains with exact, it works.
But I cannot get contains or icontains to work on any fields.

Requirements.txt:

Django==1.10.4
psycopg2==2.6.2
djangorestframework==3.5.3
channels==1.0.0
djangorestframework-jwt==1.9.0
django-filter==1.0.1
asgi-redis==1.0.0
daphne==1.0.0

Most helpful comment

Hi @xtrinch - could you post a sample URL with query params? My guess is that you're querying /api/orders?status=foo instead of /api/orders?status__icontains=foo. There is a note in the Meta.fields docs that explains the slightly different behavior of exact lookups.

All 4 comments

Hi @xtrinch.

From the description I can't see an issue. Can I advise that you try putting a breakpoint in your FilterSet's qs property and step through to see what's happening.

If you could narrow it down to a simple test case that too would help.

Filter just takes the value and builds a lookup for the ORM so the question is, _Where's that going wrong?_

Hi @xtrinch - could you post a sample URL with query params? My guess is that you're querying /api/orders?status=foo instead of /api/orders?status__icontains=foo. There is a note in the Meta.fields docs that explains the slightly different behavior of exact lookups.

@rpkilby Thanks. I was under the impression that the first item in the array becomes the default filter - I see I was wrong :)

your post is very useful for me in my project
Thanks

Was this page helpful?
0 / 5 - 0 ratings