Search code examples
pythondjangosearchdjango-querysethtmx

Adding a boolean value to a search function


I have a multi-filter function that returns Clinic results based in 4 parameters. I want to add a 5th parameter which is a BooleanField (both in model and form).

I want the field to return the corresponding elements if True, but if False, return all the elements according to the other search parameters independently of this BooleanField.

if request.htmx:
    name = request.GET.get('name')
    city = request.GET.get('city')
    ward = request.GET.get('ward')
    speciality = request.GET.get('speciality')
    english = request.GET.get('english')
    print(f'english: {english}')
    if all([len(name) == 0, len(city) == 0, len(ward) == 0, len(speciality) == 0]):
        qs = None
    else:
        qs = Clinic.objects.filter(Q(name__icontains=name) &
                                   Q(city__icontains=city) &
                                   Q(ward__icontains=ward) &
                                   Q(speciality__icontains=speciality))

I tried to add the english variable to the queryset as

Q(english_support=english)

but without success. If I print out the result, it returns None if not checked, and on if checked. How can I add the condition that if None, return all the results according to the other Q parameters and if True just add it to the other conditions?


Solution

  • You can chain multiple .filter() methods, so apply the new boolean filter only when the respective form field is True (= its value is on, which is the default value for a checkbox).

    if request.htmx:
        name = request.GET.get('name')
        city = request.GET.get('city')
        ward = request.GET.get('ward')
        speciality = request.GET.get('speciality')
    
        if all([len(name) == 0, len(city) == 0, len(ward) == 0, len(speciality) == 0]):
            qs = None
        else:
            qs = Clinic.objects.filter(Q(name__icontains=name) &
                                       Q(city__icontains=city) &
                                       Q(ward__icontains=ward) &
                                       Q(speciality__icontains=speciality))
    
            if request.GET.get('english') == 'on':
                qs = qs.filter(english_support=True)