I need to search for users table filtering by first name or last name.
Given a user John Doe Smith, where John is the First Name and Doe Smith is the Last Name.
When I search for John Smith, it should find the user above.
I know that its just a matter of implementing the solution of this SO answer, but how I do that in django-filter
and keep other Filter Fields like email
or phone
also ?
patient.py
(Only the relevant part)
class Patient(TimeStampedModel):
name = models.CharField('Name', max_length=30)
last_name = models.CharField('Last Name', max_length=30)
phone = models.CharField('Phone', max_length=14)
I just found out that method
parameter is what I was looking for found here
Basically my code ended like this:
class PatientFilter(FilterSet):
name = CharFilter(name='name', lookup_expr='icontains')
last_name = CharFilter(name='last_name', lookup_expr='icontains')
phone = CharFilter(name='phone', lookup_expr='icontains')
full_name = CharFilter(name='full_name', method='search_by_full_name')
def search_by_full_name(self, qs, name, value):
for term in value.split():
qs = qs.filter(Q(name__icontains=term) | Q(last_name__icontains=term))
return qs
class Meta:
model = Patient
fields = ['name', 'last_name', 'phone']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With