0

ユーザーがフォームに送信したテキストを含む名前をデータベースで検索するdjangoビューがあります。

検索に使用するときは、各レコードのフィールドとフィールド.filterに対してユーザーのクエリを確認します。それはすべて機能しますが、私の問題は、ユーザーが検索ボックスに空白を使用してフルネームを入力した場合(たとえば、「john」または「smith」の代わりに「John Smith」)、関数が結果を返さないことです。first_namelast_name

これらすべてにまったく新しいので、関数やフォームを変更する方法がわかりません。怠惰になってスペースキー(それは可能だと思います)などを入力できないようにすることもできますが、問題の実際の解決策を学びたいですか?

フォームとビューは次のとおりです。非常にシンプルです。

<form action="/Speakers/Search" method="get">
    <input type="text" name="q">
    <input type="submit" value=" Search ">
    </form>

完全な副次的な質問:私は行折り返しのあるテキストエディタを使用しているので、Pythonで行区切りを追加することが「安全」な場所がまだわからないことを忘れましたか?重要なのはインデントだけですか..?したがって、以下のコードをスクロールする必要があることをお詫びします。

def SearchSpeakers(request):
    if 'q' in request.GET and request.GET['q']: #2nd condition return false if emtpy string
        search = request.GET['q']
        message = "You searched for: %s." % search
        results = Speaker.objects.filter(Q(first_name__icontains=search) | Q(last_name__icontains=search))
        if not results: #returned empty
            message += " We could not find the name you entered in our Speakers List but you check back again before the event! Press clear to see the complete list again."

        return render_to_response('Speakers.html', {'speakers':results, 'query': message})
    else:
        message = "You did not enter a name."
        return render_to_response('Speakers.html',{'query':message})
4

2 に答える 2

2

より多くのQ()オブジェクトを使用できます

import operator
results = Speaker.objects.filter(reduce(operator.or_,
              (Q(first_name__icontains=term)|Q(last_name__icontains=term)
               for term in request.GET.get('q', '').split())
于 2012-06-22T14:36:17.457 に答える
1

問題は、first_nameまたはlast_nameフィールドをwhole_nameで検索していることのようです。入力をチェックし(空白またはコンマで分割)、ループ内で名前全体の各メンバーを検索するロジックを追加できます。私はDjangoに精通していませんが

search = request.GET['q']
message = "You searched for: %s." % search
for term in list(set(search.split())):
    # ...search each term and compile into a set of results
于 2012-06-22T14:03:07.340 に答える