views:

107

answers:

2

I have a contact/address app that allows users to search the database for contact entries. The current view will return an object (Entry()) and display its fields. The code is as follows:

def search_page(request): 
    form = SearchForm() 
    entrylinks = [] 
    show_results = True 
    if request.GET.has_key('query'): 
     show_results = True 
     query = request.GET['query'].strip() 
     if query:
      form = SearchForm({'query' : query}) 
      entrylinks = \
       Entry.objects.filter (name__icontains=query)[:10] 
    variables = RequestContext(request, { 'form': form, 
     'entrylinks': entrylinks, 
     'show_results': show_results
    }) 
    return render_to_response('search.html', variables)

I'd like to add an "if" statement to the view that would recognize when there are multiple objects returned (people with the same name in the database) and in such a case, divert the returned objects to a different template (which would simply list the returned objects so the user could choose which he/she'd prefer). Can anyone show what such a statement would look like? Thanks.

+2  A: 

The object returned by Entry.objects.filter (a QuerySet) has a length, meaning you can call len(entrylinks) to get the number of records returned. Thus, you can do something like this:

if len(entrylinks) == 1:
    tpl = "search.html"
else:
    tpl = "select.html"
variables = RequestContext(request, {
    "form": form,
    "entrylinks": entrylinks,
    "show_results": show_results,
})
return render_to_response(tpl, variables)
mipadi
awesome. thanx much mipadi. appreciated.
kjarsenal
+1  A: 

Rather than using len(entrylinks), you should use entrylinks.count(). The built-in count method is much faster and can save you a database query.

Josh Ourisman
Doesn't `entrylinks.count()` result in _another_ DB query? `count()` does a `SELECT COUNT(*) ...` behind the scenes.
mipadi
Agree with mipadi. In this case, `len` is actually more efficient, because you're going to need to evaluate the queryset anyway in your template.
Daniel Roseman
Crap, you're right. I was thinking about it all wrong.
Josh Ourisman