Last Updated: February 25, 2016
·
540
· bennylope

Simple Django search managers

Just a simple pattern to follow for making search/filtering views easier to comprehend, test, and maintain. Add a manager with a search method which wraps all of the queryset filtering:

def search_view(request):
    form = SearchForm(request.GET)
    if form.is_valid():
        object_list = MyModel.objects.search(form.cleaned_data)
    else:
        object_list = MyModel.objects.all()

Now conditional filtering and complex queries are encapsulated in the manager and can be tested without the view. Full post on the Wellfire Interactive blog.