【发布时间】:2012-06-24 20:01:31
【问题描述】:
我有一个 django 视图,它在我的数据库中搜索一个名称,其中包含用户在表单上提交的文本。
当我使用.filter 进行搜索时,我会根据每条记录的first_name 和last_name 字段检查用户查询。一切正常,但我的问题是,如果用户在搜索框中输入带有空格的全名(例如,“John Smith”而不是“john”或“smith”,我的函数将不会返回任何结果!
对这一切都很陌生,我不确定我将如何更改函数甚至表单。我可能只是懒惰并阻止他们输入空格键(我认为这是可能的)或其他东西,但我想了解我的问题的实际解决方案?
这是表单和视图,它们非常简单:
<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})
【问题讨论】: