I'm working with Django rest framework API, I am trying to make a filter by first_name or by 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 :
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
}
My actuel 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**
Any help would be appreciated ..
For fuzzy search lookups I recommend using this approach:
filters.py
api.py
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.
I solved my problem by modifying my class ContactFilter like this:
And in my view I just had to do this :
My request url looks like :
But I still wonder if I can have something like this in Django
What I do, is write custom FilterBackend. Something like this:
Besides basic filtering (fieldname=value pairs) I can use any Django queryset Field Lookups (__gt, __gte, __startswith,...) in my URLs like this:
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:
So restrict allowed_fields carefully and not include foreign keys that could lead to related User model.
If your requests aren't too complicated you can also use:
Which will enable '?some_field__starswith=text' sintax support in request query params.
I suppose 'startswith' can be replaced with any django standart queryset filter param.