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.

4

2 に答える 2

2

Entry.objects.filter(a )によって返されるオブジェクトには長さがあります。つまり、返されるレコードの数を取得するためにQuerySet呼び出すことができます。len(entrylinks)したがって、次のようなことができます。

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)
于 2009-11-06T17:44:26.060 に答える
1

len(entrylinks) を使用する代わりに、entrylinks.count() を使用する必要があります。組み込みの count メソッドははるかに高速で、データベース クエリを節約できます。

于 2009-11-06T18:52:23.507 に答える