I'm using django filter
on DRF with following model.
class Customer(models.Model):
passport_no = models.CharField(max_length=20, blank=True, null=True)
nic_driving_license = models.CharField(max_length=20, blank=True, null=True)
...
I'm sending either passport_no
or nic_driving_license
from the FE as id_no=<value>
. How can I specify the filterset_fields
to look for exact match on either of above fields? Following is not working since I think it does an AND match.
filterset_fields = {
'passport_no': ['exact'],
'nic_driving_license': ['exact']
}
With the suggestion of @wiaterb I was able to do this exactly. Posting the solution to help others.
Note: No need to specify filterset_fields
.
views.py
import django_filters
from django.db.models import Q
from .models import Person
class IDFilter(django_filters.FilterSet):
id_no = django_filters.CharFilter(method='search_by_id', label='Search By ID')
class Meta:
model = Person
fields = ['id_no']
def search_by_id(self, queryset, name, value):
return queryset.filter(
Q(passport_no=value) | Q(nic_driving_license=value)
)
class PersonViewSet(viewsets.ModelViewSet):
...
filterset_class = IDFilter