Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter by first name OR last name using django-filter

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)
like image 456
André Roggeri Campos Avatar asked Sep 02 '17 00:09

André Roggeri Campos


1 Answers

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']
like image 73
André Roggeri Campos Avatar answered Sep 18 '22 13:09

André Roggeri Campos