Django Filter Backend

I solved my problem by modifying my class ContactFilter like this:

import django_filters
from .models import Contact

class ContactFilter(django_filters.FilterSet):
   class Meta:
        model = Contact
        fields = {
            'first_name': ['startswith'],
            'last_name': ['startswith'],
        }
        together = ['first_name', 'last_name']

And in my view I just had to do this :

class ContactViewSet(viewsets.ModelViewSet):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializer
    filter_class = ContactFilter

My request url looks like :

http://localhost:8000/api/v1/contact/?first_name__contains=Cl&last_name__contains=Tes

But I still wonder if I can have something like this in Django

http://localhost:8000/api/v1/contacts/?first_name=Cl**&last_name=Tes**

What I do, is write custom FilterBackend. Something like this:

# views.py
from rest_framework import filters

class ObjektFilterBackend(filters.BaseFilterBackend):
    allowed_fields = ['objekt', 'naziv', 'kategorija', 'zadnja_sprememba']

    def filter_queryset(self, request, queryset, view):
        flt = {}
        for param in request.query_params:
            for fld in self.allowed_fields:
                if param.startswith(fld):
                    flt[param] = request.query_params[param]

        return queryset.filter(**flt)


class ObjektiViewSet(mixins.ListModelMixin,
                 mixins.RetrieveModelMixin,
                 viewsets.GenericViewSet):
    authentication_classes = (
        authentication.TokenAuthentication,
        authentication.SessionAuthentication)
    permission_classes = (IsAuthenticated,)
    queryset = models.Objekt.objects.all()
    serializer_class = serializers.ObjektSerializer
    filter_backends = (ObjektFilterBackend, ObjektOrderBackend,)
    ....

Besides basic filtering (fieldname=value pairs) I can use any Django queryset Field Lookups (__gt, __gte, __startswith,...) in my URLs like this:

http://localhost:8000/api/v2/objekti/?naziv__startswith=Apartma&zadnja_sprememba__gte=2018-01-01

And ObjektFilterBackend class could be easily adapted to support searching by pattern.

Just a little warning - this approach is potentially dangerous, because it allows end user to filter also by foreign key field. Something like this also works:

http://localhost:8000/api/v2/objekti/?kategorija__naziv__icontains=sobe

So restrict allowed_fields carefully and not include foreign keys that could lead to related User model.


I think the DjangoFilterBackend is mainly equality-based filtering. But you can customize the filtering method.

Also in DRF, for non exact filtering, there is the SearchFilter which makes case-insensitive partial matches searches by default.