[Answered ]-Django – how to perform search with multiple fields and ModelForm

2👍

While debugging the search view, I found that the initial if condition against request.GET only returned True for 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.

def search(request):
    errors = []
    if 'field1' in request.GET:
        field1 = request.GET['field1']
        field2 = request.GET['field2']
        field3 = request.GET['field3']
        if not ((field1 or field2) or field3):
            errors.append('Enter a search term.')
        else:
            results = MyModel.objects.filter(
                field1__icontains=field1
            ).filter(
                field2__icontains=field2
            ).filter(
                field3__icontains=field3
            )
            query = "Field 1: %s, Field 2: %s, Field 3: %s" % (field1, field2, field3)
            return render_to_response('search/search_results.html',
                    {'results': results, 'query': query})
    return render_to_response('search/search_form.html',
            {'errors': errors})

The query string 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 results above to results_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.

Leave a comment