I’m looking to build a search form using a ModelForm class, that allows a user to search for values in a Model by specific fields instead of a single field keyword search. I also want empty fields to be ignored.
I’ve looked into search engine options such as Haystack and Djapian, as well as approaching the problem manually in Django, but I don’t seem to be able to get results back when querying with multiple fields.
This is what I have so far for the view, based partially on answers to some similar questions on this site, in addition to what’s documented:
def search(request):
error = False
form = InfoForm()
if 'field1' or 'field2' or 'field3' in request.GET:
form = InfoForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
field1 = cd['field1']
field2 = cd['field2']
field3 = cd['field3']
if not(field1 or field2 or field3):
error = True
else:
query = Q()
if request.GET['field1']:
query &= Q(field1__icontains=request.GET['field1'])
if request.GET['field2']:
query &= Q(field2__icontains=request.GET['field2'])
if request.GET['field3']:
query &= Q(field3__icontains=request.GET['field3'])
results = PersonInfo.objects.filter(query).distinct()
return render_to_response('search/personsearch.html',
{'query': query,
'field1': field1,
'field2': field2,
'field3': field3,
'results': results,
},
context_instance=RequestContext(request))
return render_to_response('search/infosearch.html',
{'error': error,
'form': form},
context_instance=RequestContext(request))
I also tried this complex query straight from the documentation:
query = InfoModel.objects.get(
Q(field1__icontains=field1) |
Q(field2__icontains=field2) |
Q(field3__icontains=field3)
)
In both cases, the query string ?field1=&field2=&field3= appears appended to the URL, and the page returns with the supplied field values in the field, as expected; but neither return a result or generate an error if all fields are left blank.
I’m obviously missing something, but for the life of me I can’t figure out what. Has anyone else encountered this problem?
While debugging the search view, I found that the initial
ifcondition againstrequest.GETonly returnedTruefor one field, even if all the fields listed were in fact in the form.From there, the simplest method to achieve my multi-field search was to string
.filter()methods together. Empty fields in the search form are ignored, as hoped for, but if all fields are empty, it returns you to the search form with a properly handled error.The
querystring here now simply returns a formatted list of search terms, which you can drop into your template. But you can also return the variables directly and place them in another form on the search results page, if you want.Pagination also works nicely on the search results, which is essential for any real-world application. Rename
resultsabove toresults_list, and the code from the Django documentation on Pagination can be plugged into your view. One caveat I found, you have to add a new variable that contains your search string and include that at the front of your pagination links, or you get returned to the search form when you click the ‘next’ or ‘previous’ links as defined in the docs.Lastly, it seems to work best when you build the form in HTML instead of relying on Django’s ModelForm class. That way you don’t have to pull your hair out trying to debug form validation errors, and can define your own validation rules inside your view function.