Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a partial search filter in Django REST framework?

I'm working with the Django REST framework library and I am trying to make a filter that can filter by first_name, last_name, or by both of them. This is my ContactViewSet.py:

class ContactViewSet(viewsets.ModelViewSet):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializer
    filter_backends = (DjangoFilterBackend, )
    filter_fields = ('first_name', 'last_name')
    lookup_field = 'idContact'

My DRF's settings.py:

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
}

My current request URL looks like:

http://localhost:8000/api/v1/contacts/?first_name=Clair&last_name=Test

But I'm looking for something like this:

http://localhost:8000/api/v1/contacts/?first_name=Cl**&last_name=Tes**
like image 606
Naella Avatar asked Jul 25 '17 07:07

Naella


2 Answers

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 this:

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**
like image 87
Naella Avatar answered Sep 21 '22 21:09

Naella


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.

like image 40
Nadège Avatar answered Sep 19 '22 21:09

Nadège