[Answered ]-Python Django "and/or" searching in database

2👍

Maybe something like this:

text_fields = {
    'city': request.POST.get('city'),
    'state': request.POST.get('state'),
    'province': request.POST.get('province'),
    'used_teargas': request.POST.get('teargas'),
    'victim_1_name': request.POST.get('victim_name'),
    'victim_1_ethnicity': request.POST.get('victim_ethnicity'),
    'victim_1_age': request.POST.get('victim_age'),
    'victim_1_sex': request.POST.get('victim_sex'),
    'victim_1_status': request.POST.get('victim_status'),
}

boolean_fields = {
    'used_taser': request.POST.get('taser'),
    'used_teargas': request.POST.get('teargas'),
    'victim_1_armed': request.POST.get('victim_armed')
}

q_objects = Q()

for field, value in text_fields.iteritems():
    if value:
        q_objects |= Q(**{field+'__contains': value})

for field, value in boolean_fields.iteritems():
    if value:
        q_objects |= Q(**{field: True})

incidents = Incident.objects.filter(
    Q(datepicker__range=[date_start, date_end]), 
    Q(country__contains=country), 
    q_objects
)

The resulting query is very similar to the one you provided, the only difference is the list or ored (|) Q objects (named q_objects here) is built dynamically – that allows you to provided rules for whether a particular field should be included on that list (“if value” in that particular case. That will do exactly what you want – filter out empty strings, False values, and None values).

You should also look into dedicated search solutions like Haystack.

Leave a comment