开发者

handling multiple returned objects

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 = \
                En开发者_开发知识库try.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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜