1👍
✅
You can compose your Q
expressions conditionally:
qexpr = ( Q(first_name__icontains=post_data['first_name']) &
Q(last_name__icontains=post_data['last_name']) )
if post_data['doctor']:
qexpr &= Q(doctor=post_data['doctor'])
customers = Customer.objects.filter(qexpr)
The unconditional filter on doctor=post_data['doctor']
would evaluate to doctor=None
if nothing is selected in the doctor
input of your form, which will then translate to either doctor_id = NULL
or to doctor_id IS NULL
in the generated SQL query (not certain how Django’s ORM would handle it, and I haven’t tested), neither of which will match any records in your model.
Source:stackexchange.com