【问题标题】:How would I alter this QuerySet filter to handle user input with white space?我将如何更改此 QuerySet 过滤器以处理带有空格的用户输入?
【发布时间】:2012-06-24 20:01:31
【问题描述】:

我有一个 django 视图,它在我的数据库中搜索一个名称,其中包含用户在表单上提交的文本。

当我使用.filter 进行搜索时,我会根据每条记录的first_namelast_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})

【问题讨论】:

    标签: python django


    【解决方案1】:

    你可以使用更多Q() objects

    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())
    

    【讨论】:

      【解决方案2】:

      您的问题似乎是您正在使用全名搜索 first_name 或 last_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
      

      【讨论】:

      • 谢谢!这就是它所需要的,方便知道:) for name in list(set(search.split())): results = Speaker.objects.filter(Q(first_name__icontains=name) | Q(last_name__icontains=name))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多