0

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 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

awesome. thanx much mipadi. appreciated.
1

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.

2 Comments

Doesn't entrylinks.count() result in another DB query? count() does a SELECT COUNT(*) ... behind the scenes.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.